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:
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
Jinja2 works with Python 2.6. x, 2.7. x and >= 3.3. If you are using Python 3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.2 was dropped in Jinja2 version 2.7.
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.
Dictionaries do not have the append method. You can add a key-value pair like this though:
{% do data['location']=node.location %}
or
{% do data.update({'location': node.location}) %}
Key takeaways:
append()
.You can add the new item to the data dictionary by using {% do ... %}
tag as shown here:
{% do data.update({'location': node.location}) %}
However, for the "do" tag to work properly you need to add the jinja2.ext.do
extension to your jinja Environment.
Without the do
extension:
{%- set _ = dict.update({c.name: c}) -%}
Works in base Jinja2 on Python 3, where the __setitem__
solutions give me:
access to attribute '__setitem__' of 'dict' object is unsafe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With