jinja2中字典的默认值(可翻译) [英] default value for dictionary in jinja2 (ansible)
本文介绍了jinja2中字典的默认值(可翻译)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
jinja2的过滤器'| default()'用于未定义的变量.但这不适用于字典值.
jinja2 has filter '|default()' to works with undefined variables. But it does not work with dictionary values.
如果D可能具有或没有密钥foo(D [foo]),则为:
if D may have or not have key foo (D[foo]), than:
{{ D[foo]|default ('no foo') }}
如果未定义D,将显示'no foo',但如果定义了D但未定义D [foo],则会导致错误('dict object'没有属性'foo').
will prints 'no foo' if D is undefined, but will cause error ('dict object' has no attribute 'foo') if D is defined, but D[foo] is undefined.
有什么方法可以使词典项默认为默认值?
Is any way to make default for dictionary item?
推荐答案
使用Ansible 1.7.2对我来说似乎正常.这是我刚写的测试手册:
This appears to be working properly for me using Ansible 1.7.2. Here's a test playbook 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') }}"
这是运行它的输出:
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"
}
这篇关于jinja2中字典的默认值(可翻译)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文