【问题标题】:Jinja2 and ansible/python : jinja2.exceptions.TemplateAssertionError: no filter named 'bool'Jinja2 和 ansible/python : jinja2.exceptions.TemplateAssertionError: no filter named 'bool'
【发布时间】:2019-09-06 07:10:14
【问题描述】:

我试着翻译这行

enabled: "{{ with_postgresql | default(false) | bool }}"

带有jinja2库代码:

template = env.get_template(file)

但是结果是 KO 并且错误信息是:

jinja2.exceptions.TemplateAssertionError: no filter named 'bool'

我需要导入其他东西吗?

【问题讨论】:

  • 完成数据(playbook、cat 文件、命令、错误...)并使其成为minimal-complete-verifiable example mcve.
  • 一个简单的执行代码:from jinja2 import Template tm = Template("{{ with_packaqge | default(false) | bool }}") msg​​ = tm.render(with_packaqge=True) print(msg)
  • 问题是您的代码示例没有调用环境,正如您所想,您需要更改环境

标签: python filter ansible boolean jinja2


【解决方案1】:

解决方案是添加行:

env.filters['bool']= bool

调用get_template之前进入Jinja2环境

...
env = jinja2.Environment(loader=jinja2.FunctionLoader(spit_template))

env.filters['bool']= bool

output = env.get_template('name').render(with_postgresql = 'true')
...

我认为 bool 是一个可靠的功能。

【讨论】:

  • 一个更好的选择是使用distutils.util.strtobool
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多