我的类(class)是这样的
class Foo():
x = attrib()
y = attrib()
f = Foo(x=1, y=2)
我的模板看起来像
<html>
<body>
<span>{{x}}</span> -> instead of this I want to use foo.x
<span>{{y}}</span> -> instead of this I want to use foo.y
</body>
</html>
我使用template.render(**attr.asdict(f))
来渲染它。
相反,我只想传递 template.render(f)
并使用 {{f.x}}
和 {{f.y}}
有办法做到这一点吗? 我不断遇到错误
vars = dict(*args, **kwargs)
TypeError: 'Foo' object is not iterable
最佳答案
template.render
需要知道如何调用变量。因此,它接受 "varname": "value"
的字典,或关键字参数,例如 render(x=f.x, y=f.y)
。这正是您的 **attr.asdict(f)
表达式的计算结果;但如果您不包含 **
,它也同样有效。
要解决您的问题,只需使用关键字参数:template.render(f=f)
。这还允许您重命名变量:如果您想在模板中使用 foo.x
,请调用 template.render(foo=f)
关于python - 如何将对象实例传递给 jinja html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51735093/