【问题标题】:Wrapping multiple rows in html with twig用树枝在html中包装多行
【发布时间】:2016-02-03 18:14:57
【问题描述】:

所以我使用 twig 将数组中的一堆实体呈现给页面,我想知道是否可以将它们中的每一块包装在 html 中?

例如,如果我有 100 个实体,并且我想将每 10 个实体包装在一个带有“page”类的 div 中,这可以用 twig 实现还是我需要其他东西?

我一直在玩循环、模数等,但无法弄清楚。有什么建议吗?

我目前正在使用 for 循环将它们放到页面上,并试图弄清楚如何用 html 包装它们的组。

【问题讨论】:

标签: php html twig rows


【解决方案1】:

您可以为此使用batch 过滤器。来自Twigdocumentation

批处理过滤器通过返回带有 给定数量的项目。可以提供第二个参数并用于 填写缺少的项目:

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

或者你甚至可以使用简单的if..else 语句使用loop.index variable

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

<table>
{% for row in items %}
    {% if loop.index % 3 == 1 %}
    <tr>
    {% endif %}
        <td>{{ row }}</td>
    {% if loop.index % 3 == 0 or loop.last %}
    </tr>
    {% endif %}
{% endfor %}
</table>

如您所见,使用batch 更清晰。

【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2013-08-07
    • 2017-07-22
    • 2022-01-02
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多