使用jinja2时如何在字典对象中添加新条目? [英] How to add a new entry into a dictionary object while using jinja2?
问题描述
使用jinja2模板时,我无法在字典对象中添加新条目.
I am not able to append add a new entry into a dictionary object while using jinja2 template.
例如,在这里我使用jinja2模板,并创建了一个 data 变量,它是一个字典.在检查了某些 if 条件后,我 Want 将位置属性附加到数据对象,例如
For example, here I am using jinja2 template and I have created a data variable which is a dictionary. And after checking some if condition I WANT to append location attribute to the data object e.g.
{%- set data = {
'name' : node.Name,
'id' : node.id,
}
-%}
{% if node.location !="" %}
data.append({'location': node.location})
{% endif %}
但是我找不到实现此目标的方法,并且遇到了UndefinedError:
However I could not find a way to achieve this and am getting the UndefinedError:
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'append'
有人遇到这个问题或可以提供参考来解决这个问题吗?
我在网上搜索,但找不到解决方案,即如何在Jinja中为dict对象添加条目.
I searched the web but could not find a solution i.e. how to achieve adding an entry to the dict object in the Jinja.
我已经介绍了以下和其他网络资源:
I have referred following and other web resources:
- http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
- https://github.com/saltstack/salt/issues/27494
- http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
- In Jinja2 whats the easiest way to set all the keys to be the values of a dictionary?
- https://github.com/saltstack/salt/issues/27494
推荐答案
如果没有jinja2.ext.do
扩展名,则可以执行以下操作:
Without the jinja2.ext.do
extension, you can do this:
{% set x=my_dict.__setitem__("key", "value") %}
忽略x
变量,并使用现在已更新的字典.
Disregard the x
variable and use the dictionary which is now updated.
UPD:同样,它适用于len()
(__len__()
),str()
(__str__()
),repr()
(__repr__()
)和许多类似的东西.
UPD: Also, this works for len()
(__len__()
), str()
(__str__()
), repr()
(__repr__()
) and many similar things.
这篇关于使用jinja2时如何在字典对象中添加新条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!