如何获得for循环中的第二个元素 [英] How to get the second element in a for loop

查看:286
本文介绍了如何获得for循环中的第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Twig中有一个for循环。我试图访问for循环中的不同元素,所以我可以在我的网站上的不同地方使用它们。



让我们有一个名为'图像'的模板。在这个模板中,我有一个for循环,如下所示:

  {%图像中的图像%} 
< div> ;
< img src ={{image | url_image}}width =100height =100/>
< / div>
{%endfor%}

在另一个模板中,图像模板。所以我得到的是:

$ p $ {%include'images.html'%}

现在我所面临的问题是我只想要images.html模板中for循环的第二个元素。你是怎么做到的?



所以我想要这样的东西:

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

有人知道最好的方法是什么或者你是如何做的?你可以看到我是Twig的新手)

解决方案

你几乎已经找到了你的答案! b
$ b

使用作为条件语法:

  {%key,图片中的图片if key == elementNumber%} 
< ; DIV>
< img src ={{image | url_image}}width =100height =100/>
< / div>
{%endfor%}

然后用你需要的参数值记住 key 从0开始,所以下面的示例会给你第二个元素):

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

如果你想做一些精心制作的东西,比如如果key< elementNumber



但是,如果你一次只需要一个元素,这可能会更好,而不是for循环: p>

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


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 ;)

解决方案

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>

这篇关于如何获得for循环中的第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆