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|clean_class,

  set outer_column_classes = [

  set inner_column_classes = [

<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 %}

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?


Your question is exactly about this issue:

Allow instantiating Attribute objects within Twig


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 = [
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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