Display a template in a block

Creating the XML file contents

The XML file at app/code/Macademy/Jumpstart/view/frontend/layout/jumpstart_index_index.xmlcomes with a root page node, which you can generate with your tool of choice to save some time. You can also extract this node and its format from any other Magento layout XML file.

Layout XML files contain a body node that references the body of the page. Within it usually comes a referenceContainer node that refers to an existing container element that has already been added to the layout someplace by another module. Containers in Magento are structural elements used to contain other containers and blocks. We’ll set the name attribute to content to reference the content container, which is the main component that contains all other elements in the Magento layout.

Next, we’ll create a new block node. All blocks should have a name, and we’ll define this using the name attribute. I usually like to prefix my module blocks with the vendor name and module name, so let’s name this one macademy_jumpstart_welcome. Also, our block node should refer to the template that it will output using the template attribute.

The value of this attribute follows the syntax: VendorName_ModuleName, in this case, Macademy_Jumpstart. This will be followed by two colons and the name of our template, relative to the view/frontend/templates directory of our module. So this will simply be welcome.phtml.

<?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">
    <body>
        <referenceContainer name="content">
            <block name="macademy_jumpstart_welcome" template="Macademy_Jumpstart::welcome.phtml"/>
        </referenceContainer>
    </body>
</page>

After making changes to the layout XML, remember to clear the Magento cache using the bin/magento cache:flush command. Upon refreshing our page, the updated template will be rendered.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock