2017-09-15 106 views
0

我有下面的模板:Jinja2的变量超出范围

{% 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我的意思是这个问题的工作,该转子始终是一个不更改。

那我怎么能解决以下问题?

+0

https://fabianlee.org/2016/10/18/saltstack-setting-a-jinja2-variable-from-an-inner-block-scope/ – Mazzy

+0

那么你试图解决什么问题?例如,对“'value”进行单一修改:“{{rotator - 1 + idx}}”“给出了一个人可能认为合理的结果。但是,人们应该怎么知道你的期望是什么? – techraf

+0

我的期望是,旋转器必须具有以下模式1,2,3,1,2,3等... – Mazzy

回答

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" 
}, 

我离开结束,因为你没有指定如何处理它要么做。