Last active
October 13, 2020 00:21
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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