Search code examples
symfonytwigshuffletwig-extension

Twig: How to write a for loop with an integrated if condition based on a value


the situation

  • I have a little symfony twig app, where I run a for loop to get all items shown.
  • I want to let the user decide if his content is rendered in a specific order or randomly, for which I will use the twig extension function shuffle().
  • If the user activates the checkbox shuffle in the backend, it will output yes for the variable activateShuffle.
  • I want to activate the twig shuffle() extension, if the above mentions variable is yes

the problem

I have found a way to handle the requirement. But with the following way, I need to duplicate some code which seems very wrong to me.

Current Code:

{% if activateShuffle == 'yes' %}
    {% for item in images|shuffle() %}
        <div>
            <h1>{{ item.title }}</h1>
            <img src="{{ asset('images/')}}{{ item.imagename }}"/>
        </div>
    {% endfor %}
{% else %}
    {% for item in images %}
        <div>
            <h1>{{ item.title }}</h1>
            <img src="{{ asset('images/')}}{{ item.imagename }}"/>
        </div>
    {% endfor %}
{% endif %}

the solution

is there a way to define the if condition within the for loop? so that it checks if a variable has a specific value and adds the extension? So maybe something like this:

{% for item in images if activateShuffle == 'yes' add |shuffle() %}
    <div>
        <h1>{{ item.title }}</h1>
        <img src="{{ asset('images/')}}{{ item.imagename }}"/>
    </div>
{% endfor %}

Thank you for your help


Solution

  • You could change the images variable depening on the value of activateShuffle before your loop like this:

    {% if activateShuffle == 'yes' %}
        {% set images = images|shuffle() %}
    {% endif %}
    
    {% for item in images %}
        <div>
            <h1>{{ item.title }}</h1>
            <img src="{{ asset('images/')}}{{ item.imagename }}"/>
        </div>
    {% endfor %}