Python 在 jinja2 中使用数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32030387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
working with arrays in jinja2
提问by Денис Балобин
I'm passing an array object from a view in my Flask server to the jinja2 template. Let's say the name is aList. When I try to change a value inside of aListlike this:
我正在将一个数组对象从我的 Flask 服务器中的视图传递给 jinja2 模板。假设名称是aList. 当我尝试aList像这样更改里面的值时:
in Flask:
在烧瓶中:
aList = ['a', 'b', 'c']
in the template:
在模板中:
{% set aList[0] = "work, dammit!" %}
I get this error that tells me that "=" is expected instead of "[" in the template.
我收到这个错误,告诉我在模板中需要“=”而不是“[”。
Can someone tell what the right way of working with arrays is in jinja2?
有人能说出在 jinja2 中使用数组的正确方法是什么吗?
采纳答案by t-8ch
First: Logic should not be handled in the template!
第一:逻辑不应该在模板中处理!
Second: If you really have to:
第二:如果你真的必须:
If jinja does not accept the array syntax you should be able to work around it by using operator.setitemfrom the stdlib. (Be sure to add operatorto globals)
如果 jinja 不接受数组语法,您应该能够通过使用operator.setitemstdlib来解决它。(一定要添加operator到全局变量)
{% set foo = [0, 1, 2, 3, 4] %}
{% set _ = operator.setitem(foo, 'some stuff') %}
{{ foo }}

