计算 Jinja2 / Ansible 中所需的空间

Calculate needed spaces in Jinja2 / Ansible

我正在尝试根据字典中最长的单词计算所需的 space。

似乎变量 num 没有将它的值传递给第二个内部循环。

我基本上是在尝试计算 space 的数量以正确对齐列。

{% for module in modules %}
module "{{ module.name }}" {
  source = "{{ module.source }}"
  {% set num = 1 %}
{% for n in module.vars.keys() %}
  {% if  num < n|length %}
    {% set num = n|length %}
  {% endif %}
    {{ num }}: {{ n }} 
{% endfor %}
{% for m in module.vars %}
    {{ num }}
  {{ m }} {{ '= "' + module.vars[m]|indent(width=num) }}"
{% endfor %}
}

你是对的,你不能通过这种方式将变量从循环中取出来。请参阅 docs 中的 "Scoping behavior"。

一个选择是使用他们的建议并创建一个命名空间:

{% set ns = namespace(num=0) %}
{% for n in module.vars.keys() %}
  {% if ns.num < n|length %}
    {% set ns.num = n|length %}
  {% endif %}
    {{ ns.num }}: {{ n }} 
{% endfor %}

对于您的情况,有一个更简单、更简洁的解决方案:您可以计算表达式中的最大宽度。使用 map() 获取长度列表,并使用 max 过滤器获取最大长度:

{% set indent_width = module.vars.keys() | map("length") | max %}
{% for m in module.vars %}
   {{ m }} {{ '= "' + module.vars[m]|indent(width=indent_width) }}"
{% endfor %}