【问题标题】:Jinja2 variable out of scopeJinja2 变量超出范围
【发布时间】:2017-09-15 22:08:34
【问题描述】:

我有以下模板:

{% set rotator = 1 %}
{% for idx in range(1, count|int + 1) %}
{% if rotator == 4 %}
  {% set rotator = 1 %}
{% endif %}
{
  "id": "{{ '%02d' % idx }}",
  "value": "{{rotator}}"
},
{% set rotator = rotator + 1 %}
{% endfor %}

由于此处讨论的问题How to increment a variable on a for loop in jinja template?,此模板不起作用 对于doesn't work,我的意思是旋转器始终是一个并且不会改变。

那么我该如何克服以下问题?

【问题讨论】:

  • 那么您要解决的问题是什么?例如,对"value": "{{rotator - 1 + idx}}" 的一次更改会给出一个人可能认为合理的结果。但是怎么会有人知道你的期望是什么?
  • 我的期望是rotator必须有以下模式1,2,3,1,2,3等...
  • 这不是您的期望,这是您尝试的解决方案引入的问题的近似解决方案 - 不需要任何“rotator”。

标签: ansible jinja2 ansible-template


【解决方案1】:

模板:

{% for idx in range(1, count|int + 1) %}
{
  "id": "{{ '%02d' % idx }}",
  "value": "{{ (idx+2)%3+1 }}"
},
{% endfor %}

结果(count=7):

{
  "id": "01",
  "value": "1"
},
{
  "id": "02",
  "value": "2"
},
{
  "id": "03",
  "value": "3"
},
{
  "id": "04",
  "value": "1"
},
{
  "id": "05",
  "value": "2"
},
{
  "id": "06",
  "value": "3"
},
{
  "id": "07",
  "value": "1"
},

我留下了结尾,,因为你也没有指定如何处理它。

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2021-10-04
    • 2020-12-24
    • 2013-10-26
    • 2016-01-09
    • 2018-09-19
    相关资源
    最近更新 更多