user3939059 user3939059 - 29 days ago 22
HTML Question

jinja - loop over single list of items, add to table from left to right

I am looking to output a list of items in a table in a jinja2 template.

current code:

<table style="width:100%">
{% for i in sales %}
<tr>
<td>{{i}}</td>
</tr>
{% endfor %}
</table>


Which results in:

item
item
item
item
...


Expected output:

item item item
item item item
item item item
item item item
...


I would like the output to be spread over three columns, ie. loop from left to right in the table and then start a new row after 3 items.

roy roy
Answer

You can use batch

>>> import Jinja2
>>> t = jinja2.Template("{% for i in items|batch(3) %}{{i}}{% endfor %}")
>>> items = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> print t.render(items=items)
>>> ['1', '2', '3']['4', '5', '6']['7', '8', '9']
Comments