本文介绍了jinja2 中字典的默认值(ansible)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 中字典的默认值(ansible)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:06