Skip to content

Instantly share code, notes, and snippets.

@SpacemanPete
Last active October 13, 2020 00:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpacemanPete/c6f576f3a176f7d2b8eb6784a1ab0c5f to your computer and use it in GitHub Desktop.
Save SpacemanPete/c6f576f3a176f7d2b8eb6784a1ab0c5f to your computer and use it in GitHub Desktop.
Adding first/last/odd/even classes to a twig loop in Drupal 8
{# Borrowed some syntax from https://gist.github.com/NikLP/cb9adc963036d1ffd8896928de2b9b7a and expanded upon it. #}
<div{{ attributes.addClass('container') }}>
{% for item in items %}
{# NB! notation: loop.index is 1 start, loop.index0 is zero start. #}
{# Add first/last/odd/even classes to elements in loop #}
{# odd/even #}
{% set loopClasses = [] %}
{% if loop.index is odd %}
{% set loopClasses = loopClasses|merge(["odd"]) %}
{% else %}
{% set loopClasses = loopClasses|merge(["even"]) %}
{% endif %}
{# first #}
{% if loop.first %}
{% set loopClasses = loopClasses|merge(["first"]) %}
{% endif %}
{# last #}
{% if loop.last %}
{% set loopClasses = loopClasses|merge(["last"]) %}
{% endif %}
<div{{ item.attributes.addClass( loopClasses ) }}>{{ item.content }}</div>
{% endfor %}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment