2

I have this simple element model and I'm trying to add dynamic class within loop. So every time a model outputs, It outputs dynamic class. Can't go for another loop within loop, in case I could, therefor It'd be easy.

            {% set tags = slide.foodTags %}
            {% if tags %} 

            <div>   
                  {% for tag in tags %}                     
                        <span class="{# dynamic-class #}">
                            {{ tag.title }}
                        </span>
                  {% endfor %}
            </div> 

           {% endif %}
  • 1
    What do you want the dynamic class to be based on? The tag's ID? It's position in the loop? An element related to the tag? – Peter Tell Mar 16 '15 at 21:08
  • Based on count. {{ loop.index }} helped. Thanks for concern @Peter Tell – Dominik Krulak Mar 17 '15 at 7:59
3

Not really sure what you're wanting the dynamic portion to be based on, but if it's something like the loop count, then you can do something like this:

{% set tags = slide.foodTags %}

{% if tags %} 

    <div>   
        {% for tag in tags %}                     
            <span class="dynamic-{{ loop.index }}">
                {{ tag.title }}
            </span>
        {% endfor %}
    </div> 

{% endif %}
  • I wanted do loop count, but I only knew method {% for i in 1..entries|length %}. I couldn't put it to my model, but now I can do it with {{ loop.index }}, which I had no idea, It does such great thing. Thank you @Brad Bell – Dominik Krulak Mar 17 '15 at 8:03
  • 1
    Be advised the loop variable contains other useful properties as well, such as first, last and odd. If you needed to style the first item different from the rest, for instance, you could write class="{{ loop.first ? 'first' }}" – or if you needed to style odd/even items you could write class="{{ loop.odd ? 'odd' : 'even' }}". – Mats Mikkel Rummelhoff Mar 17 '15 at 12:10
4

I can't comment yet to reply directly to Mats Mikkel Rummelhoff's comment above, but just in case someone comes across this and is looking to alternate styles instead of basing it on the loop.index count.

You would do so using the Twig odd or even tests

{{ loop.index is odd ? 'odd' : 'even' }}

or

{{ loop.index is even ? 'even' : 'odd' }}

There is no loop.odd key

  • 1
    So you meant to comment and wound up leaving a perfectly acceptable answer? Nice work, MalTek! :) – Matt Stein May 9 '17 at 3:51
  • :) I went to leave a comment, but it said I needed 50 points before I could. But I was allowed to add an answer. It was the second time I had come across this thread and tried loop.odd, so thought it might have happened to others! (and looking out for my future self, haha) – MalTek May 10 '17 at 4:50

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.