你会如何用 Twig 制作一个两列的表?
我这辈子都不知道如何在 Twig 循环中的每个 OTHER 迭代中添加一个 </tr><tr>
.
I can't for the life of me figure out how to add a </tr><tr>
every OTHER iteration in a Twig loop.
例如:
$numArray = array(12,13,14,15,16,17,18);
传递给树枝,我会循环一个表格:
Passed to twig, I would loop a table like:
<table>
{% for num in numArray %}
<tr>
<td>
{{num}}
</td>
</tr>
{% endfor %}
</table>
这将输出:
+-----------+
| 12 |
+-----------+
| 13 |
+-----------+
| 14 |
+-----------+
| 15 |
+-----------+
| 16 |
+-----------+
| 17 |
+-----------+
| 18 |
+-----------+
我想做的是得到这样的东西:
What I'd like to do is get something like this:
+-----------+-----------+
| 12 | 13 |
+-----------+-----------+
| 14 | 15 |
+-----------+-----------+
| 16 | 17 |
+-----------+-----------+
| 18 | |
+-----------+-----------+
但我终其一生都想不出一种方法来将我的行输入与任何看起来不老套的东西交替.老实说,我什至无法工作.有办法吗?或者,我是否应该编写自己的扩展程序?
But I can't for the life of me figure out a way to alternate my row input with anything that doesn't seem hacky. Honestly I can't even get hacky to work. Is there a method for this? Or, should I be looking to write my own extension?
推荐答案
正确的做法是使用 batch 过滤器.它是 1.12.3 中的新功能.
The proper way of doing this is using the batch filter. It is new in 1.12.3.
<table>
{% for row in numArray|batch(2) %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
参考:http://twig.sensiolabs.org/doc/filters/batch.html
相关文章