Jinja2实现模板高度自定义
1.Jinja2 For循环
{% for item in all_item %}
{{ item }}
{% endfor %}
案例1:为远程主机生成服务器列表,该列表从192.168.37.201web01.magedu开始,到192.168.37.211 web11.magedu结束
{% for id in range(201,211) %}
192.168.37.{{ id }} web{{ "%2d"|format(id-200) }}.magedu
{% endfor %}
2 Jinja2 If条件
{% if my_conditional %}
...
{% endif %}
案例2:如果变量PORT被存在,则bind-address=0.0.0.0:{{PORT变量的值}},否则,bind-address=0.0.0.0:3306。
{% if PORT %}
bind-address = 0.0.0.0:{{ PORT }}
{% else %}
bind-address = 0.0.0.0:3306
{% endif %}
3 Jinja多值合并
{% for node in groups['db'] %}
{{ node | join('') }}:5672
{% if not loop.last %} #如果是最后一次迭代,为True
{% endif %}
{% endfor %}
4 Jinja default()设定
bind-address = 0.0.0.0:{{ PORT | default(3306)}} #若PORT变量没有定义则为3306

浙公网安备 33010602011771号