1

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_attribute(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>
1

1 Answer 1

2

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

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

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.

Your Answer

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

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