Jinja 2 delete an item from dictionary inside a template

How to delete an item from a dictionary inside jinja2 template?

I couldn’t find it in jinja2 documentation, but seems that jinja2 assignments support python methods for dictionaries. del statement won’t work, but this will:


{% set _dummy=mydict.pop('key') %}
{% if 'key' not in mydict %}
'key' was deleted
{% endif %}

To avoid using unnecessary variable, you may enable jinja jinja2.ext.do extension. For ansible, this is done with jinja2_extensions configuration directive. That makes code look clearer:


{% do mydict.pop('key') %}
{% if 'key' not in mydict %}
'key' was deleted
{% endif %}



License: This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License Share: share on reddit share on hacker news share on facebook share on twitter share on linkedin share on slashdot

No comments

You today

Comments are closed