Dynamic use of templates in Jinja2


Question

I have to following scenario:

a python list of python dictionaries l = [a,b,c,...,n] each element of the list is a python dictionary that looks something like this:

d = {}
d['type'] = 5
d['content'] = 'somestring'

Now i want all dictionaries as a list in in a main template. However each dictionary's content should be rendered by a child template. Which template to use to render the content should be defined by the type variable of the dictionary.

Any hints on how this can be accomplished using Jinja2 (I'm using it via Flask if that helps..)

Thanks!

1
24
5/23/2011 7:20:57 PM

Accepted Answer

If anyone needs it:

{% for d in dicts %}
  {% set template = d.type + '.html' %} {% include template %}
{% endfor %}

then in the template you can access the content like so:

{{ d.content }}

Thanks to donri from the #pocoo channel on freenode !

48
5/24/2011 6:54:53 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon