【问题标题】:Foreach loop with multiple element in Twig template engine在 Twig 模板引擎中具有多个元素的 Foreach 循环
【发布时间】:2015-03-11 09:09:20
【问题描述】:

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

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

这是我的数据:

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

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

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

但这正是我在 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>

在 Twig 中存在一种快速的方法来执行此操作,还是我应该使用另一个子数组层以不同的方式准备数据?

【问题讨论】:

    标签: php twig template-engine


    【解决方案1】:

    看来您需要使用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>
    

    它将呈现:

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

    来源:Twig Documentation

    【讨论】:

    • 谢谢。批处理是我的答案!
    • 树枝文档链接已失效。 :-(
    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2013-05-27
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多