How to add a new entry to a dictionary object when using jinja2?

I cannot add a new entry to the object dictionary when using the jinja2 template.

For example, here I use the jinja2 template and created the data variable, which is a dictionary. And after checking some if conditions, I want to add a 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 get an UndefinedError:

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

Has anyone encountered this problem or can provide a link to solve it?

I searched on the Internet, but could not find a solution, that is, how to achieve adding an entry to a dict object in Jinja.

I referenced the following and other web resources:

  1. http://cewing.imtqy.com/training.codefellows/assignments/day22/jinja2_walkthrough.html
  2. In Jinja2, what is the easiest way to set all keys to dictionary values?
  3. https://github.com/saltstack/salt/issues/27494
+14
source share
4 answers

Without the jinja2.ext.do extension jinja2.ext.do 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.

+13
source

There is no add method in dictionaries. You can add a key-value pair like this:

 {% do data['location']=node.location %} 

or

 {% do data.update({'location': node.location}) %} 
+9
source

Key takeaway:

  • Vocabulary
  • does not support append() .
  • You can add a new item to the data dictionary using the {% do ... %} tag, as shown below:

     {% do data.update({'location': node.location}) %} 
  • However, for the "do" tag to work correctly, you need to add the jinja2.ext.do extension to the jinja2.ext.do environment.

+7
source

Without do extension:

 {%- set _ = dict.update({c.name: c}) -%} 

Works in a Jinja2 database on Python 3, where __setitem__ solutions give me:

 access to attribute '__setitem__' of 'dict' object is unsafe 
0
source

All Articles