使用jinja2时如何在字典对象中添加新条目? [英] How to add a new entry into a dictionary object while using jinja2?

查看:326
本文介绍了使用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:

  1. http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
  2. https://github.com/saltstack/salt/issues/27494
  1. http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
  2. In Jinja2 whats the easiest way to set all the keys to be the values of a dictionary?
  3. 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屋!

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