在Jinja2中动态使用模板

时间:2022-01-27 20:47:41

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:

一个python词典的python列表l = [a,b,c,...,n]列表中的每个元素都是一个python字典,如下所示:

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..)

关于如何使用Jinja2完成任何提示(如果有帮助,我通过Flask使用它)

Thanks!

1 个解决方案

#1


45  

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 !

感谢来自freenode的#pocoo频道的donri!

#1


45  

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 !

感谢来自freenode的#pocoo频道的donri!