3

I want to add a class to the <a>-Tag of a Field that consists of a URL-link and a link text (it's a field of type "Link") and the name of the field is content.field_c_button_link So with twig in my HTML-File I want to have something like this:

{{ content.field_c_button_link.0.addClass('button blue') }}

How can I add a class properly?

maidi
  • 3,219
  • 6
  • 27
  • 55

2 Answers2

4

Why not piece the anchor tag together manually? That way you have complete control over everything. Something like this in your template

<a href="{{content.field_url.0['#url']}}" class="custom classes">{{content.field_url.0['#title']}}</a>
jsheffers
  • 1,602
  • 19
  • 41
0

Ok, this is horrible but it's the only way I found to get this to work:

If you look at the default drupal build array for your link you should see that content.field_c_button_link.0 is an array(4)

'#type' => string(4) "link"
'#title' => string(15) "Big Blue Button"
'#options' => array(0)
'#url' => object Drupal\Core\Url(11) 

So, to set classes directly on the <a> tag we have to load '#options' (which is presently empty) with the right setup of subarrays

'#options' => array(1)
'attributes' => array(1)
'class' => array(2)
string(6) "button"
string(4) "blue"

The only way I could find to do this within twig was to use a series of temps and merging them with the original array because twig wouldn't parse anything else I tried:

{% set temp = {'attributes': {'class': ['button','blue']}} %}
{% set temp2 = content.field_c_button_link.0 %}
{% set temp2 = temp2|merge({'#options': temp}) %}
{% set temp3 = content.field_c_button_link|without('0')  %}
{% set temp3 = temp3|merge({'0': temp2}) %}
{% set content = content|merge({'field_c_button_link': temp3}) %}

Note the |without which is a Drupal/twig filter. I had to use it to remove the empty '0' element to avoid having the link print twice.

Please tell me there is an easier way.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
dan433
  • 96
  • 3