47

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.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
NomadAlien
  • 9,090
  • 6
  • 25
  • 22

1 Answers1

94

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>
emartinelli
  • 1,019
  • 15
  • 28
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 1
    Fantastic! Thanks Sean, you are a life safer! Been struggling with this for too long now and making no progress :-) – NomadAlien Feb 09 '12 at 08:50