Jinja2动态变量构建 [英] Jinja2 dynamic variable building

查看:54
本文介绍了Jinja2动态变量构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jinja模板获取了一个具有许多变量名称的对象,此属性各不相同,因此它们的名称也不同,我正在寻找一种基于前缀和for循环访问此属性的方法:

My jinja template gets an object which has many variable names, this attributes vary and so their names, I am looking for a way to access this attributes based on a prefix and a for loop:

{% for i in Object.vars %}
    <h1> {{ Object.attribute_ + i }} </h1>
{% endfor %}

我正在尝试访问Object.attribute_1,Object.attribute_2等.上面的代码当然行不通,但是我无法考虑这样做的方法.

I'm trying to access Object.attribute_1, Object.attribute_2 and so on. the code above of course won't work, but I can't think on a way of doing this.

推荐答案

请记住,在模板文件中执行过多的逻辑将导致(长期的)维护代码的问题.

Keep in mind that doing too much logic in your template files will cause (long term) issues to maintain your code.

我想说的是,使用

I would say, keep your logic outside of the template and create a list of your objects before rendering the template, using the getattr() function:

for i in Object.vars:
    list_of_objects.append(getattr(Object, 'attribute_' + i))

现在,在渲染模板时,将列表传递给这样:

Now when rendering the template pass the list to like that:

render_template('page.html', list_of_objects=list_of_objects)

这篇关于Jinja2动态变量构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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