Merge twig attributes with object

To change multiple parts of an Attributes object in twig, merge it with an object keyed with updated attributes.

Use the output to create a new attributes object and overwrite the attributes variable.

{% set attributes = create_attribute(attributes|merge({
  'id': 'theme__page_header',
  'role': 'banner'
  'class': 'page-header'
})) %}

<header {{ attributes }}>
</header>
<header
  data-component-id="mantra_theme:page_header"
  id="theme__page_header"
  role="banner"
  class="page-header">
</header>

Alternatively use the do tag.

{# Single line #}
{% do attributes.setAttribute('id', 'theme__page_header') %}
{% do attributes.setAttribute('role', 'banner') %}
{% do attributes.addClass('page-header') %}

{# Multi line #}
{% do
  attributes
    .setAttribute('id', 'theme__page_header')
    .setAttribute('role', 'banner')
    .addClass('page-header')
%}
Tags
Articles