php 在 Twig 模板引擎中具有多个元素的 Foreach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28982375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:11:23  来源:igfitidea点击:

Foreach loop with multiple element in Twig template engine

phptwigtemplate-engine

提问by Tobia

I'm using Twig as template framework for my PHP web application.

我使用 Twig 作为我的 PHP Web 应用程序的模板框架。

I would like to know if there is a fast way to get many element in a foreach block.

我想知道是否有一种快速的方法可以在 foreach 块中获取许多元素。

This is my data:

这是我的数据:

users=>[
 ["name"=>"User1"],
 ["name"=>"User2"],
 ["name"=>"User3"],
 ["name"=>"User4"],
 ["name"=>"User5"],
 ["name"=>"User6"]
]

This would be a standard loop (each item):

这将是一个标准循环(每个项目):

<ul>
    {% for user in users %}
        <li>{{ user.name }}</li>
    {% endfor %}
</ul>

But this is what I need in block of nelements (in this example n=3)

但这是我在n 个元素块中需要的(在本例中n=3

<ul>
    <li>User1</li>
    <li>User2</li>
    <li>User3</li>
</ul>
<ul>
    <li>User4</li>
    <li>User5</li>
    <li>User6</li>
</ul>

Exists a fast way to do this in Twig or should I prepare the data in a different way with a one more subarray layer?

在 Twig 中存在一种快速的方法来做到这一点,还是我应该用另一种子阵列层以不同的方式准备数据?

回答by Rodin Vasiliy

Looks like you need to use batchfilter:

看起来你需要使用batch过滤器:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

It will render:

它将呈现:

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</td>
        <td>e</td>
        <td>f</td>
    </tr>
    <tr>
        <td>g</td>
        <td>No item</td>
        <td>No item</td>
    </tr>
</table>

Source: Twig Documentation

来源:Twig 文档