Magento2 – Display phtml Block in Another Block Page

blockslayoutmagento2magento2.2.2template

As M1 if I need to display just some phtml in another block or page, so we have to create it in a current theme then we can retreive it via xml or the other block

xml:

<the_layout_handle>
    <reference name="root">
        <block type="core/template" name="block1" template="path/to/file.phtml">
    </reference>
</the_layout_handle>

then in the other file we get it like this: <?php echo $this->getBlockHtml('block1'); ?>

phtml:

or directly like this: <?php echo $this->getLayout()->createBlock('core/template')->setTemplate('path/to/file.phtml')->toHtml(); ?>

Question :

Directly in file I know that bu how to reproduce the same thing via xml in M2 ?

phtml:

echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Luma::path/to/file.phtml")->toHtml();

Issue:

I have some phtml in app/design/frontend/Magento/Luma/template/block1.phtml

i want to display it in home page, so in content I have this: {{block class="Magento\Framework\View\Element\Template" name="block1" template="Magento_Luma::template\block1.phtml"}} but it doesn't work !

Best Answer

If you want to show a custom phtml file on home page, I think there are 2 ways to do it.

First way is by inserting this into admin homepage:

{{block class="Magento\Framework\View\Element\Template" name="block1" template="Magento_Theme::block1.phtml"}}

And you create your block1.phtml in:

/app/design/frontend/{vendor}/{theme}/Magento_Theme/templates/block1.phtml

Second way is by inserting the template block like this (for example inside the main content container):

<referenceContainer name="content">
    <block class="Magento\Framework\View\Element\Template" name="block1" template="Magento_Theme::block1.phtml" before="-" />
</referenceContainer>

In:

/app/design/frontend/{vendor}/{theme}/Magento_Cms/layout/cms_index_index.xml

Use the before attribute to position the new block where you want inside the content container.

For example before="other_block_name" positions the new block before the other_block_name block.

You also have to create the block1.phtml in Magento_Theme/templates

Btw, you can change the template location to any other core or custom module. Magento_theme is just a default example.