3

When is the <body> tag needed in layout XML, particularly when extending existing layouts?

The documentation provides examples where tags like <referenceBlock> are contained inside <body>, but it seems to work just as well when they are included directly under the root.

Documented style:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="something">
        ...
        </referenceBlock>
    </body>
</page>

Also seems to work:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceBlock name="something">
    ...
    </referenceBlock>
</page>

Per the XSD, only the former is allowed, but maybe Magento's logic just isn't strict about that?

2 Answers 2

1

maybe Magento's logic just isn't strict about that

Well the issue is that if you don't keep your XML files valid (in according to their XSDs), you're likely to get your logs filled with messages similar to the following:

Cache file with merged layout: LAYOUT_frontend_STORE1_67a17789838b48d9a0ad068240a963441 and handles 1column: Please correct the XML data and try again. 

Which might be okay if you cannot perform the task otherwise, but ignoring those XSDs for no reason doesn't seem wise.

Plus, please remember that the logic handling reading that XML file might also change in the future versions. For example, <body> (as opposed to <head>) was probably intended in order to reference different parts of the HTML document, and the implementation on this distinction might catch up in the future, breaking your module if it doesn't target <body> explicitly.

1
  • 1
    Thanks! I knew following the XSD was going to be best, but this helps explain specifically why. Mar 20, 2017 at 13:45
0

Magento 2 uses tag when you want to call reference block or container inside particular page

for example:

Let's assume you want to add a template on product details page. You need to create new xml file catalog_product_view.xml in your module. You xml code might look like this:

<?xml version="1.0"?>
<body>
  <referenceContainer name="product.info.main">
    <block class="Lapisbard\Catalog\Block\Product\View\Extra"
           name="product.view.extra"
           template="Lapisbard_Catalog::product/view/extra.phtml"
           after="product.info.overview">
    </block>
 </referenceContainer>
 </body>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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