Skip to content

Instantly share code, notes, and snippets.

@NikLP
Last active February 25, 2021 12:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NikLP/cb9adc963036d1ffd8896928de2b9b7a to your computer and use it in GitHub Desktop.
Save NikLP/cb9adc963036d1ffd8896928de2b9b7a to your computer and use it in GitHub Desktop.
Set zebra-style (odd/even) classes in twig loop in drupal 8 (bootstrap) theme
<div{{ attributes.addClass('container') }}>
{% for item in items %}
{# NB! notation: loop.index is 1 start, loop.index0 is zero start #}
<div class="row {{ loop.index0 is odd ? 'zebra-odd' : 'zebra-even' }}">
<div{{ item.attributes }}>{{ item.content }}</div>
</div>
{% endfor %}
</div>
@marcvangend
Copy link

marcvangend commented Feb 19, 2019

Thanks! Or if you prefer to not add an extra div:

<div{{ attributes.addClass('container') }}>
  {% for item in items %}
    {% set zebra_class = loop.index0 is odd ? 'zebra-odd' : 'zebra-even' %}
    <div{{ item.attributes.addClass(zebra_class) }}>
      {{ item.content }}
    </div>
  {% endfor %}
</div>

Personally I use the loop.index for this, but that's a matter of taste I guess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment