2

In Drupal 8, how can you add new attributes to be rendered into the twig file?

I want to provide a region.html.twig that can be extended for subtheming.

So, I want the default to be:

{%
  set wrapper_classes = [
    'region',
    'region-' ~ region|clean_class,
    'container',
    'container--100',
  ]
%}

{%
  set outer_column_classes = [
    'container__col',
  ]
%}

{%
  set inner_column_classes = [
    'container__inner',
  ]
%}

<div{{ wrapper_attributes.addClass(wrapper_classes) }}>
  <div{{ outer_column_attributes.addClass(outer_column_classes) }}>
    <div{{ inner_column_attributes.addClass(inner_column_classes) }}>
      {% block content %}
        {{ content }}
      {% endblock %}
    </div>
  </div>
</div>

Simply making them arrays or strings as you would in D7 doesn't work - they never reach the twig template.

I noticed that Bartik uses the Attribute class to create new/empty Attributes. Is this kosher to do, exactly?

use Drupal\Core\Template\Attribute;

function mytheme_preprocess_region(&$variables) {
  $variables['wrapper_attributes'] = new Attribute();
  $variables['outer_column_attributes'] = new Attribute();
  $variables['inner_column_attributes'] = new Attribute();
}

When I do that, my new attributes appear and are rendered in the template. Is this even worth doing, or is it a lot more trouble to extend templates and manipulate them?

1 Answer 1

3

Your question is exactly about this issue:

Allow instantiating Attribute objects within Twig

Problem/Motivation

Sometimes you have an array of attributes and it would be nice if you could addClass, removeClass, setAttribute, etc. rather than trying to do array manipulation.

Proposed resolution

Add a function to our Twig extension to allow creating an Attribute object from an array of attributes.

Issue: https://www.drupal.org/node/2616756

And the change record for 8.3.x:

{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}
</div>

https://www.drupal.org/node/2818293

Your Answer

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

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