Skip to content

Instantly share code, notes, and snippets.

@NikLP

NikLP/zebra.html.twig

Last active Jul 14, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@marcvangend 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
You can’t perform that action at this time.