How to add row count CSS classes to Views output in Drupal 8

Last modified: 
Saturday, July 1, 2017 - 19:13
Dan Eveland
Dan Eveland's picture

For some reason, view rows no longer get those handy numbered classes you can use to format row based on placement in the results. All rows are given "views-row" only. Not helpful.

I was able to fix this by copying the Views twig template to my theme's template/views directory. In my case, I am using an unformatted list, so I used views-view-unformatted.html.twig.

Now, I could have made the template more specific, to a particular content type, for example. However, just adding a class really should not break anything, and I might want to reference that in my SASS as I continue working on the site, so I left it at it's default.

The existing code looks like this:

{% if title %}
   <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
     set row_classes = [
       default_row_class ? 'views-row',
   <div{{ row.attributes.addClass(row_classes) }}>
     {{ row.content }}
{% endfor %}

As you can see, the classes added are only "views-row".

To add the additional class, I simply changed this line to

default_row_class ? 'views-row', 'views-row-' ~ loop.index,

This will result in each row being given "views-row-1", the next row gets "views-row-2", and so forth.