Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

python - How to add a new entry into a dictionary object while using jinja2?

I am not able to append add a new entry into a dictionary object while using jinja2 template.

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 %}

However I could not find a way to achieve this and am getting the UndefinedError:

jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'append'

Has anyone faced this issue or could provide a reference to solve this?

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. 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without the jinja2.ext.do extension, you can do this:

{% set x=my_dict.__setitem__("key", "value") %}

Disregard the x variable and use the dictionary which is now updated.

UPD: Also, this works for len() (__len__()), str() (__str__()), repr() (__repr__()) and many similar things.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...