Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic use of templates in Jinja2

Tags:

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!

like image 262
joekr Avatar asked May 23 '11 19:05

joekr


People also ask

How are templates reused in Jinja2?

To reuse a Jinja template you use the Jinja built-in {% extends %} tag. The {% extends %} tag uses the syntax {% extends <name> %} to reuse the layout of another template. This means that in order to reuse the layout in listing 4-5 defined in a file base.

What is the main purpose of Jinja2 template usage with Ansible?

Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.


1 Answers

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 !

like image 159
joekr Avatar answered Dec 21 '22 06:12

joekr