Calling Custom PHTML Files in Magento 2
In Magento 2, you can call custom PHTML files from various locations such as other PHTML files, XML layout, static blocks, and CMS pages. This guide will walk you through the process of calling your custom file located at app/design/frontent/vendor_name/theme/Magento_Theme/templates/html/test.phtml.
Calling a Custom PHTML File in Another PHTML File
To include a PHTML file within another PHTML file, use the {block type="core/template" template="Magento_Theme::html/test.phtml"} syntax.
Here’s an example of calling test.phtml inside a custom PHTML file named custom.phtml:
<?xml version="1.0"?>
<page layout="2columns-left">
<body>
<referenceBlock name="content">
<block type="core/template" template="Magento_Theme::html/test.phtml"/>
</referenceBlock>
</body>
</page>
Calling a Custom PHTML File in XML Layout
To include a custom PHTML file in the main layout of your theme, update your theme.xml file with the following content:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="default"/>
<referenceBlock name="content">
<block type="core/template" template="Magento_Theme::html/test.phtml"/>
</referenceBlock>
</page>
Calling a Custom PHTML File in a Static Block
To use the custom PHTML file as a static block:
- Go to Content > Blocks and click on “Add New Block”.
- Fill in general information (Name, Title).
- Under Content, choose Edit with template, then select Custom from the list.
- In the ‘Template’ field, enter
Magento_Theme::html/test.phtml. - Click “Save Block”.
Now you can use this static block anywhere in your store by using its unique identifier.
Calling a Custom PHTML File in a CMS Page
To include a custom PHTML file within a CMS page:
- Go to Content > Pages.
- Click on the desired page or click “Add New Page”.
- In the content field, use the following syntax:
{block type="core/template" template="Magento_Theme::html/test.phtml"} - Click “Save Page”.
Conclusion
In this guide, we explored how to call a custom PHTML file in various locations within your Magento 2 store. Whether you’re using it in another PHTML file, XML layout, static block, or CMS page, the process remains straightforward once you understand the syntax.
Remember, always ensure that your PHTML files are properly named and located according to the Magento 2 directory structure for optimal performance and security.
For more detailed information on Magento 2 development best practices, feel free to explore our comprehensive guides at Laravel Company.