2015-11-03 81 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> 

更清晰。