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.

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 %}
  • This worked: {{ cycle(themes, loop.index) }}. Thanks, mate! – Jay Dec 2 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. – Christopher Robert Kennedy Dec 2 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 Dec 4 at 16:22
  • 1
    Ah, true. You don’t need to use math, though. You can just use loop.index0 instead! – Christopher Robert Kennedy Dec 4 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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