Magento 2 provides a flexible way to organize and reuse code by allowing you to call one .phtml (PHP HTML) file from another. This can be particularly useful when you want to include common elements, such as headers, footers, or sidebars, across multiple pages. In this tutorial, we will explore how to call a .phtml file within another .phtml file in Magento 2.
Step 1: Identify the File to be Included
Firstly, determine which .phtml file you want to include in another .phtml file. For the purpose of this tutorial, let’s assume you want to include the file named “included.phtml” in another file called “main.phtml”. Make sure both files are located within the same theme or module directory.
Step 2: Open the Main .phtml File
Open the “main.phtml” file in your preferred text editor. This is the file where you want to include the contents of “included.phtml”.
Step 3: Add the PHP Code
Inside the “main.phtml” file, locate the position where you want to include the contents of “included.phtml”. At that location, insert the following PHP code:
<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Vendor_Module::included.phtml")->toHtml(); ?>
Make sure to replace “Vendor_Module” with the appropriate path to the module or theme where the “included.phtml” file resides.
Step 4: Save and Apply the Changes
Save the “main.phtml” file, and you’re done! The contents of “included.phtml” will now be rendered and displayed at the specified location within “main.phtml”.
Step 5: Clear the Cache (if necessary)
If you have Magento’s cache enabled, you may need to clear it to see the changes take effect. This can be done via the Magento admin panel or by running the following command in the terminal:
php bin/magento cache:clean
That’s it! You have successfully called a .phtml file within another .phtml file in Magento 2. This method allows you to reuse code and improve the maintainability of your Magento theme or module. Feel free to explore further possibilities and leverage the flexibility offered by Magento 2’s templating system.