Magento 2 – How to Add .phtml File on All Pages

extensionsfrontendmagento2page-layoutsxml

I want to add my custom.phtml file on the top of all pages.

How can I do this using custom module ?

Any suggestion would be appreciated.

Thanks

Best Answer

Add this code in your custom theme or module in default.xml:

app/design/frontend/Namespace/Themename/Magento_Theme/layout/default.xml

<referenceContainer name="after.body.start">
    <block class="Magento\Framework\View\Element\Template" 
           name="custom.file" 
           before="-" 
           template="Magento_Theme::html/custom.phtml"
    />
</referenceContainer>

you can also place it in your module:

app/code/Vendor/Module/view/frontend/layout/default.xml

<referenceContainer name="after.body.start">
    <block class="Vendor\Module\Block\Blockname" 
           before="-" 
           template="Vendor_Module::html/custom.phtml"
    />
</referenceContainer>

In this case the template must be saved under app/code/Vendor/Module/view/frontend/templates/html/custom.phtml

Related Topic