Call a constructed variable name in Jinja2 template?

余生颓废 提交于 2019-12-12 05:07:39

问题


Is there a way in Jinja2 to construct a variable name and then call it? I want to do something like this:

{% for type in ('Students', 'Faculty', 'Groups') %}
    {% set import_name = 'latest_' + type|lower + '_import' %}
    {{ type }}: {{ import_name.created_at }}
{% endfor %}

I would expect the output to be something like this:

Students: 5/26/2016
Faculty: 5/25/2016
Groups: 5/25/2016

I have the variables latest_students_import, latest_faculty_import, and latest_groups_import set in the template scope, and would like to avoid having a large conditional in my for loop. I set import_name based on the type, and then try to "call" import_name. I want something like {{ call(import_name) }}. Is this possible, or is there another way I can go about this?

In this case, I suppose I could do it in reverse order loop through the three template variable names, and then "print" the shortened name, capitalized, but I would prefer to do it this way.


回答1:


One possibility is to create a dict or a list on the server-side which contains your variables. You can then send that object to Jinja as a template variable. As it stands you are just setting import_name equal to string, which won't have the .created_at attribute.



来源:https://stackoverflow.com/questions/37471434/call-a-constructed-variable-name-in-jinja2-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!