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

&lt;section {{ attributes }}&gt;
  &lt;div&gt;{{ content.body }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_subtitle }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_category }}&lt;/div&gt;
  {{ content.field_link }} /* has its own options and attributes */
&lt;/section&gt;


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_attribute(content.field_link.0['#attributes']) %}
&lt;a href="{{ content.field_link.0['#url'] }}" {{ attributes }}&gt;
  &lt;div&gt;{{ content.body }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_subtitle }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_category }}&lt;/div&gt;
  &lt;div&gt; {{ content.field_link.0['#title'] }} &lt;/div&gt;
&lt;/a&gt;
According to the syntax your declaration is a little off. The function is also create_attribute, not create_attributes.

The {{ attributes }} variable in a node twig template won't hold what you think it holds for the link tag. So, you will need to create a new one.

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

You probably want something like this:

{% set link_attributes = create_attribute() %}
{% set link_href = content.field_link.0['#url'] %}
{% set link_title = content.field_link.0['#title'] %}

&lt;a{{ link_attributes.setAttribute('href', link_href).setAttribute('title', link_title }}&gt;
  &lt;div&gt;{{ content.body }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_subtitle }}&lt;/div&gt;
  &lt;div&gt;{{ content.field_category }}&lt;/div&gt;
  &lt;div&gt; {{ content.field_link.0['#title'] }} &lt;/div&gt;
&lt;/a&gt;


Unfortunately, since you are wrapping fields with the value of a link field, this might be more manual than you would prefer. This is because Drupal is not rendering the field, you are creating html on the fly - link fields in particular are tricky because there is often the case of wrapping data with an anchor in say, a card display format or a clickable CTA. I am not sure if anyone has found better methods of achieving this.

I wonder if anyone has written an extension that will in fact let you render a link field but intake other fields in a tag like you mentioned in another question, so you could wrap them.