3

If I have multiple attributes that I want to set to an element in a twig template it can get quite long since each attribute requires setAttribute(attribute name, attribute value).

Based on my IRC conversation (I don't remember who it was), it looks like it is not possible to set multiple attributes at once, like it is possible with CSS classes.

So I would like to know what would be a "pretty" way of setting multiple attributes in a twig template. I presume a loop of some kind.

1
  • We might be able to do this as a backwards compatible API addition, feel free to create a core issue. You're right that it's not currently possible and you'd need multiple setAttribute lines.
    – star-szr
    Commented Dec 1, 2015 at 21:33

2 Answers 2

4

If you are adding the attributes in Twig you can set multiple attributes by chaining the setAttribute calls like this:

{{ attributes.setAttribute('id', 'value').setAttribute('data-info', 'value'); }}
1
  • 1
    This worked for me in d8.
    – ymdahi
    Commented Oct 31, 2020 at 1:16
0

Are you limited to using twig to do this?

If you are open, you can try a template_preprocess_field hook to add the attributes.

Maybe you can inspire from this.

// template_preprocess_field().
{% for item in items %}
  <div {{ attributes }}>
    {{ item.content }}
  </div>
{% endfor %}

function mytheme_preprocess_field(&$variables) {
  // If you need to use values from another field, you can build an array and use that to populate the necessary attributes.

  $variables['attributes']['id'] = 'some-id';
  $variables['attributes']['class'] = 'some-class';
  $variables['attributes']['custom_attribute'] = 'custom attribute value';
}

Your Answer

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