Skip to main content

joeri poesen / bio / blog / contact

Home / Articles / Adding alternating class names to Drupal 8 Views rows via twig

Here's a a quick and easy snippet to add alternating class names to your views rows, also referred to as 'zebra' tables or 'striped backgrounds'.

1. Copy

/core/modules/views/templates/views-view-unformatted.html.twig

to

/themes/custom/yourtheme/templates/views-view-unformattted--yourviewname.html.twig

2. Replace yourviewname with your view's machine name.

3. Change the following:

  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

to

  {%
    set row_classes = [
      default_row_class ? 'views-row',
      cycle(['even', 'odd'], loop.index0),
    ]
  %}

Explanation

cycle()

A core twig function that cycles through a given array of values.

loop.index0

Indicates the position (index) of the iterator during the looping, starting at 0.

More info on twig functions: https://twig.sensiolabs.org/doc/2.x/functions/index.html