How to build up a HTML table with a simple for loop in Jinja2?

NomadAlien picture NomadAlien · Feb 8, 2012 · Viewed 74.5k times · Source

I'm just learning Jinja2. I have never done any templating before so I find the documentation very confusing right now.

How do I do build up a HTML table with a simple FOR loop? My template looks something like this:

{% for item in items %}
<TR>
   <TD class="c1"><IMG src="favicon.ico"></TD>
   <TD class="c2">{{date}}</TD>
   <TD class="c3">{{id}}</TD>
   <TD class="c4"><SPAN>{{position}}</SPAN></TD>
   <TD class="c5"><SPAN>{{status}}</SPAN></TD>
</TR>
{% endfor %}

My python code looks like this:

import jinja2
loader = jinja2.FileSystemLoader('./index.html')
env = jinja2.Environment(loader=loader)
template = env.get_template('')
print template.render(date='2012-02-8', id='123', position='here', status='Waiting')

I can't seem to generate any tables. I also don't know if this is the best way to populate a table with several fields.

Answer

Sean Vieira picture Sean Vieira · Feb 9, 2012

Just pass items to template.render as a keyword argument - it should be a list (really any iterable will do) of items. If you need sub-items use a class or a dictionary. In the simplest case, you can use a dictionary:

items = []
for i in range(1, 11):
    i = str(i)

    # dict == {}
    # you just don't have to quote the keys
    an_item = dict(date="2012-02-" + i, id=i, position="here", status="waiting")
    items.append(an_item)

# ... your code here ...

template.render(items=items)

And then your Jinja code would change slightly:

<table>
{% for item in items %}
<TR>
   <TD class="c1"><IMG src="favicon.ico"></TD>
   <TD class="c2">{{item.date}}</TD>
   <TD class="c3">{{item.id}}</TD>
   <TD class="c4"><SPAN>{{item.position}}</SPAN></TD>
   <TD class="c5"><SPAN>{{item.status}}</SPAN></TD>
</TR>
{% endfor %}
</table>