Magento 2 – Custom Attribute for Container

containersmagento2

Have hunted round for this but can't find an answer.
As the title suggests I want to add a custom attribute to a container.

I currently have a container in layout.xml as such;

<container name="my.custom.container" as="my_custom_container" htmlTag="div" htmlClass="myCustomContainer" htmlId="customContainer">

which generates

<div class="myCustomContainer" id="customContainer"></div>

as expected.

How do I add a custom attribute to this?
E.g. (As to to end up with)

<div class="myCustomContainer" id="customContainer" customAttribute></div>

Thanks

Best Answer

Unfortunately, there's no way you can do this via XML out of the box.

Magento 2 handles the htmlTag, htmlId and htmlClass via the Magento/Framework/View/Layout.php file under the _renderContainer method:

protected function _renderContainer($name)
{
    $html = '';
    $children = $this->getChildNames($name);
    foreach ($children as $child) {
        $html .= $this->renderElement($child);
    }
    if ($html == '' || !$this->structure->getAttribute($name, Element::CONTAINER_OPT_HTML_TAG)) {
        return $html;
    }

    $htmlId = $this->structure->getAttribute($name, Element::CONTAINER_OPT_HTML_ID);
    if ($htmlId) {
        $htmlId = ' id="' . $htmlId . '"';
    }

    $htmlClass = $this->structure->getAttribute($name, Element::CONTAINER_OPT_HTML_CLASS);
    if ($htmlClass) {
        $htmlClass = ' class="' . $htmlClass . '"';
    }

    $htmlTag = $this->structure->getAttribute($name, Element::CONTAINER_OPT_HTML_TAG);

    $html = sprintf('<%1$s%2$s%3$s>%4$s</%1$s>', $htmlTag, $htmlId, $htmlClass, $html);

    return $html;
}

As you can see, this method does not render any extra attributes than the ones I mentionned.

A alternative would be to use JavaScript to add the attribute based on the id you've given to your tag, for example:

jQuery('#customContainer').attr('customAttribute','customValue);