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.

  • 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. – Cottser Dec 1 '15 at 21:33

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'); }}

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 }}
{% 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, privacy policy and cookie policy