php - 用 twig 在 html 中包裹多行

标签 php html twig rows

所以我使用 twig 将数组中的一堆实体渲染到页面,我想知道是否可以将它们的每个 block 包装在 html 中?

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

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

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

最佳答案

您可以为此使用batch过滤器。来自 Twig documentation :

The batch filter "batches" items by returning a list of lists with the given number of items. A second parameter can be provided and used to fill in missing items:

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

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

{% 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 更加清晰。

关于php - 用 twig 在 html 中包裹多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33501743/

相关文章:

php - Mongodb 安装不使用 PHP

javascript - 如何更改 pdf 页面上的图标?

twig - 如何获取 Shopware 6 中所有其他 channel 的当前产品或类别 url 等效项?

php - 如何使用 php 控制 .htaccess 或如何在 .htaccess 文件中输入 php 代码

javascript - 从用户生成的 li 列表中的 ahref 链接创建数组

python - 如何从 HTML 标题中获取引用的字符串?

php - twig: IF 有多个条件

php - For 循环的最后一次迭代,如果条件与 Twig

php - var/www/文件夹外的图片链接? (Linux,PHP)

html - 在两个 jquery datepicker 表之间填充