For css purpuses I want to add custom class name to the first item in view.

<article class="myclass"></article>

I need the number in views-view-fields--viewname.html.twig to make some logic expression like

if(view-num == 1) {
    <article class="myclass"></article> 
} else { 

or maybe in one of the variables I get in fields {{fields.view_number.content}}


The fields template is probably not the best place. Normally you would do this in the views style plugin. Grid has such options built in, for Unformatted you can add

loop.first ? 'views-row-first',

to views-view-unformatted.twig.html:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
    set row_classes = [
      default_row_class ? 'views-row',
      loop.first ? 'views-row-first',
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
{% endfor %}
  • is there a way to add into the classes inside row.content? I have there <article class="breaking"> <a href="{{fields.view_node.content}}"> <img src="{{fields.field_image.content}}"> <h2>{{fields.title.content}}</h2> </a> <p>{{fields.body.content}}</p> </article> – Andy Core Jun 8 '18 at 17:16
  • I've replied to your comment, now you can remove first-child from the css .views-row-first article { // some styles here only for first item } – 4k4 Jun 9 '18 at 9:26

No need for Twig, just do it with CSS:

.name_of_your_view_parent_container article:first-child {
  // seome styles here only for first item
  • For some reason particulaly first-chid not working in all browsers. I had problems with it in chrome. So counting views number would be preferable – Andy Core Jun 8 '18 at 15:33

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.