Skip to main content
2 of 3
added 15 characters in body
usernameabc
  • 2.8k
  • 5
  • 48
  • 98

How to append options and classes into a custom attribute in Twig?

In our twig template we have a need to wrap certain fields with a Link field. In the existing twig template there already exist an attributes variable (accessed by adding attributes), but we have a need to have a custom one. Couldn't find any documentation on if you can pass options and attributes from one field to a custom twig attribute.

Is there a way to append all options and classes from a field's attributes into a custom attribute in a Twig template without any hook_preproceess_hook?

Existing node--article.html.twig

<section {{ attributes }}>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
  {{ content.field_link }} /* has its own options and attributes */
</section>

Desired output

/* pass the options and attributes from field_link into the a_attr */
/* This did not result in what we wanted */
{% set a_attr = create_attributes(content.field_link.0['#attributes']) %}
<a href="{{ content.field_link.0['#url'] }}" {{ attributes }}>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
  <div> {{ content.field_link.0['#title'] }} </div>
</a>
usernameabc
  • 2.8k
  • 5
  • 48
  • 98