如何开始循环。

发布于 2025-02-12 14:03:46 字数 359 浏览 0 评论 0原文

项目名称列表

{% for item in selection %}
  <div>{{ item.name }}</div>
  {% if loop.index % 4 == 0 %}
    <div class="xyz">
      <p>Content</p>
    </div>          
  {% endif %}
{% endfor %}

在一个小树枝模板中,显示了每4个项目后用来添加DIV的 。是否有一种方法可以在每个第四项以“#2之后”的位置开始时显示第二个DIV?因此,最后,我得到两个Divs在每个第二个项目之后交替进行交替?

In a twig template showing a list of item names I use

{% for item in selection %}
  <div>{{ item.name }}</div>
  {% if loop.index % 4 == 0 %}
    <div class="xyz">
      <p>Content</p>
    </div>          
  {% endif %}
{% endfor %}

to add a div after every 4th item. Is there a way to show a second div after every 4th item starting with the position "after #2"? So in the end I get the two divs alternating after every second item?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紧拥背影 2025-02-19 14:03:46

使用过滤器 batch在树枝中创建重复结构。
以下片段将按两个分组,使您更容易交替交替您想要的

{% for values in items|batch(2) %}
    {% for value in values %}
        <div>{{ value }}</div>
    {% endfor %}
    {% if loop.index0 is even %}
        <div class="xyz">Div 1</div>
    {% else %}
        <div class="xyz">Div 2</div>
    {% endif %}
{% endfor %}

demo

It's far easier to use the filter batch to create repeating structures in twig.
The following snippet will group the items by two, making it easier to alternate the extra div you want

{% for values in items|batch(2) %}
    {% for value in values %}
        <div>{{ value }}</div>
    {% endfor %}
    {% if loop.index0 is even %}
        <div class="xyz">Div 1</div>
    {% else %}
        <div class="xyz">Div 2</div>
    {% endif %}
{% endfor %}

demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文