2015-11-03 82 views
2

因此,我正在使用树枝来呈现数组中的一堆实体到页面,我想知道是否有可能将它们的每个块都包装在html中?例如,如果我有100个实体,并且我想每隔10个用“页面”类来包装div,这是可能的,还是需要别的东西?用树枝在html中包装多行

我一直玩的周期,模数等,但无法弄清楚。有什么建议么?

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

+2

查看'batch' - http://twig.sensiolabs.org/doc/filters/batch.html –

+0

或者您可以使用'loop.index'变量添加'if..else'语句:http: //twig.sensiolabs.org/doc/tags/for.html#the-loop-variable – chapay

+0

谢谢你们 - 非常有用的东西。添加一个答案,并接受它;) –

回答

2

您可以使用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> 

甚至可以使用使用loop.indexvariable简单if..else声明:正如你可以看到使用batch

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

更清晰。