1

I have a loop of a list of regions on a project, this could be an infinite list of areas as my client's customer-base grows.

The project branding has four key colours, I have these in an array:

{% set themes = [
    'yellow',
    'red',
    'teal',
    'blue'
] %}

What I'm looking to do is grab one of these themes as I loop over my regions with a basic {% for region in regions %}, then on the 5th, 9th and so on loop jump back to #1.

1 Answer 1

2

Do you mean to have it just assign them one after the other? If so, then you can just use Twig’s cycle function.

{% set themes = [
    'yellow',
    'red',
    'teal',
    'blue'
] %}

{% for region in regions %}
 <a href="{{ region.url }}" class="text-{{ cycle(themes, loop.index) }}">{{ region.title }}</a>
{% endfor %}
4
  • This worked: {{ cycle(themes, loop.index) }}. Thanks, mate!
    – Jay
    Commented Dec 2, 2019 at 20:31
  • 1
    Ah, good catch! That’ll teach me to write from my meatbrain and not refer to the docs. I’ve updated the response accordingly, including documentation. Commented Dec 2, 2019 at 20:38
  • Another update, the array starts at 0 whilst the loop started at 1... so loop.index - 1 was needed to start from the start. 🤷🏻‍♂️
    – Jay
    Commented Dec 4, 2019 at 16:22
  • 1
    Ah, true. You don’t need to use math, though. You can just use loop.index0 instead! Commented Dec 4, 2019 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.