How to get the second element in a for loop

2019-08-27 19:00发布

问题:

I have a for loop in Twig. I'm trying to access different elements in a for loop so I can use them in different places on my website.

Let'say I have a template called 'images'. Inside that template I have a for loop like so:

{% for image in images %}
<div>
  <img src="{{ image | url_image }}" width="100" height="100" />
</div>
{% endfor %}

In a different template I'm trying to include this 'images' template. So what I have is this:

{% include 'images.html' %}

The problem I'm facing right now is that I only want the second element from the for loop in the images.html template. How do you do that?

So I want something like this:

<div>
{% include 'images.html' with {'second element'} only %}
</div>

Does anyone know what the best approach is or how do you do that? I'm pretty new to Twig as you can see ;)

回答1:

You almost already found your answer!

Use the for with condition syntax:

{% for key,image in images if key==elementNumber %}
<div>
  <img src="{{ image | url_image }}" width="100" height="100" />
</div>
{% endfor %}

And call you template with the parameter's value you need (keeping in mind that key starts at 0, so the example bellow will give you the second element):

<div>
{% include 'images.html' with {elementNumber: 1} %}
</div>

This syntax is useful if you want to do some "elaborated" things like if key<elementNumber

But if you need only one element at a time, this might be better, instead of the for loop:

<div>
  <img src="{{ images[elementNumber] | url_image }}" width="100" height="100" />
</div>