I want to prevent using the loop twice in twig symfony3

I have multiple images and I want to make this carousel. But I don't want to iterate over the images twice.

Can this be done?

My code:

<div id="main-slider">
    {% for image in images %}
        <img src="/images/{{ image.url }}"/>
    {% endfor %}
</div>
<div id="main-slider-nav">
    {% for image in images %}
        <img src="/images/{{ image.url }}"/>
    {% endfor %}
</div>

      

As you can see, the loop is there twice. Is there a good way not to do this?

+3


source to share


1 answer


If you prefer, you can create a string with dynamic values ​​(image tag lists) and then use a div in the container, like so:

    {%set accumulator = '' %}

    {% for image in images %}
        {%set accumulator = accumulator ~ '<img src="/images/'~image.url~'"/>' %}
    {% endfor %}


<div id="main-slider">
 {{ accumulator|raw }}
</div>
<div id="main-slider-nav">
 {{ accumulator|raw }}
</div>

      



Twigfiddle sample works here

Hope for this help

+3


source







All Articles