Skip to main content

How to add row count and even/odd CSS classes to Views output in Drupal 8

Submitted by Dan Eveland on Tue, 03/24/2020 - 18:13
Resulting HTML from this article

For some reason, view rows no longer get those handy numbered classes and even/odd 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 its default file name.

This is what my code looks like:

{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {% set oddeven = 'even' %}
  {% if loop.index is odd %}
    {% set oddeven = 'odd' %}
  {% endif %}
  {%
    set row_classes = [
      default_row_class ? 'views-row', 'views-row-' ~ oddeven, 'views-row-' ~ loop.index,
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

The code in bold adds row numbers and odd/even classes.

Drupal