Magento 2 – How to Add Block into PHTML File

blocksmagento2

I'm using Magento 2 and I want to add block to all my category pages , by directly writing it into the code in the app/design/frontend/Venustheme/yume/Magento_Catalog/templates/product/list.phtml page , there is any way to call the block there, and not through the admin panel?

Best Answer

In your theme folder, add a Magento_Catalog/layout/catalog_category_view.xml layout file. Load your block into the parent block with the following:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="category.products.list">
            <block name="your.cms.block" as="something" class="Magento\Cms\Block\Block">
                <arguments>
                    <argument name="block_id" xsi:type="string">[put your block ID here]</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

In your list.phtml simply call <?php echo $block->getChildHtml('something') ?>. Of course you should name your blocks differently, but I hope you got the general idea.

Related Topic