在Jinja2模板中调用构造的变量名称? [英] Call a constructed variable name in Jinja2 template?

查看:125
本文介绍了在Jinja2模板中调用构造的变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jinja2中有没有一种方法可以构造一个变量名然后调用它?我想做这样的事情:

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 %}

我希望输出是这样的:

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

我在模板作用域中设置了变量last_students_import,latest_faculty_import和latest_groups_import,并希望避免在for循环中使用较大的条件.我根据类型设置了import_name,然后尝试调用" import_name.我想要类似{{call(import_name)}}的内容.这可能吗,或者我还有其他方法可以解决这个问题?

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.

推荐答案

一种可能性是在包含您的变量的服务器端创建dictlist.然后,您可以将该对象作为模板变量发送到Jinja.就目前而言,您只需将import_name设置为等于字符串,就不会具有.created_at属性.

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.

这篇关于在Jinja2模板中调用构造的变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆