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.
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With