The default value for the dictionary in jinja2 (possibly)

jinja2 has a filter '| default () 'for working with undefined variables. But it does not work with dictionary values.

if D may or may not have the key foo (D [foo]), than:

{{ D[foo]|default ('no foo') }} 

will print "no foo" if D is undefined, but will lead to an error (the "dict object" does not have the attribute "foo") if D is defined, but D [foo] is undefined.

Is there a way to make the default dictionary?

+8
jinja2 ansible
Mar 05 '15 at 18:33
source share
1 answer

It seems to work correctly for me using Ansible 1.7.2. Here is the test tutorial I just wrote:

 --- - hosts: localhost vars: D: 1 : "one" 2 : "two" tasks: - debug: var=D - debug: msg="D[1] is {{ D[1]|default ('undefined') }}" - debug: msg="D[3] is {{ D[3]|default ('undefined') }}" 

And here is the result of its launch:

 TASK: [debug var=D] *********************************************************** ok: [localhost] => { "D": { "1": "one", "2": "two" } } TASK: [debug msg="D[1] is one"] *********************************************** ok: [localhost] => { "msg": "D[1] is one" } TASK: [debug msg="D[3] is undefined"] ***************************************** ok: [localhost] => { "msg": "D[3] is undefined" } 
+9
Mar 05 '15 at 19:10
source share



All Articles