问题描述
for循环内部的值无法在for循环外部使用。
{% set facility = "NULL" %}{% if s['log-filter'] is not none %}{% for PRI in s['log-filter'] %}{% set facility = PRI['facility'] %}test1 {{ facility }}{% endfor %}test2 {{ facility }}{% endif %}
显示结果
test local7test2 NULL
根本原因
facility只在for 循环内部作用域中,在内部修改外部依然无法获取。
jinjia2跟Python一样也是使用栈的数据结构,先进后出,顺序执行。
解决办法
官方文档中提到使用namespace的方式解决上述问题。
Template Designer Documentation — Jinja Documentation (3.0.x)
实际测试
{% set ns = namespace(facility='any', severity='error') %}{% if s['log-filter'] is not none %}{% for PRI in s['log-filter'] %}{% set ns.facility = PRI['facility'] %}test {{ ns.facility }}{% set ns.severity = PRI['level']['equal'] | first %}test1 {{ ns.severity }}{% endfor %}test2 {{ ns.facility }}{% endif %}