0

I am trying to move page.main.title to child block of my custom block on custom page. I have defined one block in my layout file with template assigned to it. I want to show page title in between the html of this block's template.

So I've added another block inside it and rendered it in the template using <?= $block->getChildHtml('custom.child.block') ?>.

custom_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <block class="Magento\Framework\View\Element\Template" name="custom.block" template="My_Module::parent_template.phtml">
            <block class="Magento\Framework\View\Element\Template" name="custom.child.block" as="custom.child.block"/>
        </block>
        <move element="page.main.title" destination="custom.child.block" before="-"/>
    </body>
</page>

parent_template.phtml

<div class="demo-content">
    <?= $block->getChildHtml('custom.child.block') ?>
</div>

Unfortunately the page title is not getting moved to child block of custom block. However it is being moved to custom block without any issue.

Can you please help me to understand the thing I am trying to do is possible or not. Thanks in advance.

1

Your child block has no template and will output basically nothing. Change it to container, ie.:

<block class="Magento\Framework\View\Element\Template" name="custom.child.block" as="custom.child.block"/>

change to:

<container name="custom.child.block"/>

Containers outputs all their children HTML, so if you move page title block to this container, it should be rendered in a proper place.

BTW. You don't need to class="Magento\Framework\View\Element\Template" to your blocks - this is a default value. Also, you don't need to specify as="custom.child.block".

5
  • I will check with this. – Rahul Barot May 27 at 11:22
  • Biarda If I add container then how can I render this container in parent block's template. As I need it between some html code. That is why I am using getChildHtml – Rahul Barot May 27 at 13:54
  • You can use containers just like normal blocks. So, <?= $block->getChildHtml('custom.child.block') ?> will render the container. – Michał Biarda May 27 at 14:39
  • Thanks @Michal. It worked. – Rahul Barot May 28 at 4:28
  • @RahulBarot Cool! I'm glad I could help :-). – Michał Biarda May 28 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.