Magento 2 – Add Custom Attribute to Container in layout.xml

layoutmagento2

I would like to add more than one "Schema.org" to a Magento 2 Product-Layout.

In default Magento 2 the attribute for "Product-Schema" is added to body-tag, I would like to move this attribute to a container-div.

I found this thread: Magento 2 container custom attribute

But I don't think jQuery is a solution for a valid schema-structure.

So is the only solution to override the "_renderContainer" function, or can I replace a container with a template block?

Thanks

Best Answer

In order to have the Product schema.org markup somewhere other than the default location of the body tag, you need to first remove the default Magento output.

It is possible to "unset" the schema.org body attributes added by default by adding the following layout update for the default handle (i.e. in default.xml in your theme or a module):

 <body>
    <attribute name="itemtype" value="" />
    <attribute name="itemscope" value="" />
 </body>

Now you're able to place the itemtype and itemscope markup elsewhere as needed. Do this either in templates or read on for how to do it via adding attributes to containers in layout XML, as the title of your question seems to request.

Adding arbitrary attributes to existing or new containers is not possible by default. However, by extending Magento 2 it is possible to do it without altering _renderContainer (which is a really really bad idea and not necessary.)

I actually needed to do something similar to you and the OP of your linked question, and have posted a solution to that specific problem there: Magento 2 container custom attribute. Go check that out, it should get you the solution to the other part of your question.