1

How to add class to first fields in views?

I think that I need to add one if but I dont know what argument to put in if...

So how to add class just for first field in views-view-fields template.

{% for field in fields -%}
{%
        set colors = [
        'color-'~cycle(["red","yellow"],loop.index),
        loop.first ? 'first',
        loop.index== "1"?'color-first',
        ]
%}
        <b {{ field.element_attributes.addClass(colors) }}> {{ field.content }}</b>
{%- endfor %}

This code do this :

enter image description here

  • Why not add this in the view itself? You can add classes to the field wrapper, field label and field content of a views field itself. You can also change the HTML element that each of those use to be whatever you want. – mradcliffe Jun 16 '16 at 20:29
  • first fields as in the first row only? – No Sssweat Jun 17 '16 at 4:23
  • you want to add a class of red and yellow? – No Sssweat Jun 17 '16 at 9:05
  • I want to have class first for first field and that red and yelow alternating turns. – SakaSerbia Jun 17 '16 at 9:08
  • you want row 1 to be red, row 2 to be yellow, row 3 to be red, row 4 to be yellow...etc.. ?? – No Sssweat Jun 17 '16 at 9:12
4

You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}
| improve this answer | |
  • Why code when you can do this using the Views UI? – No Sssweat Jun 17 '16 at 8:42
  • 1
    Code is beter, because if somebody look for 2 years my code he would know where to found that class. Views UI is not good idea, because people forget to look there. Thank for sugestion to use preprocess field hook. But I would like to to this with twig, if I found how. Its somethinkg new and I would like to learn to use that in drupal 8. – SakaSerbia Jun 17 '16 at 8:56
1

I solve this problem by using loop.first. The joke was that in

views-view-unformatted.html.twig add loop.

{% for row in rows %}
    {% if loop.first %}
       <b class="is-visible">{{ row.content }}</b>
    {% else %}
       <b> {{ row.content }}</b>
    {% endif %}
{% endfor %}

And the code in views-view-fields.html.twig stay normal.

 {% for field in fields -%}
        {{ field.content }}
{%- endfor %}

On this way you add class to first field of fields.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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