26

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 Answer 1

56

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 !

Sign up to request clarification or add additional context in comments.

1 Comment

follow up question (sorry for the necro): is it possible to make the dictionary keys read dynamically? say, in the list of dicts, the dicts do not follow the same structure. how i can have jinja2 iterate through each dict, and then iterate through each key and print the key-value pair?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.