【问题标题】:padding/ljust with ansible template and jinja使用 ansible 模板和 jinja 填充/ljust
【发布时间】:2021-11-24 08:15:05
【问题描述】:

我正在寻找一种使用这本词典在 ansible 中创建模板的方法。

data= {
  "_dictionary": {
    "keyone": "abc",
    "rtv 4": "data2",
    "longtexthere": "1",
    "keythree": "data3",
    "keyfour": "data1234",
  }
}

模板输出应具有以下格式:

 keyone          abc
 keytwo          data2
 longtexthere    1
 keythree        data3
 keyfour         data1234

使用 python 我可以创建它:

w = max([len(x) for x in data['_dictionary'].keys()])
for k,v in data['_dictionary'].items():
    print('    ', k.ljust(w), '  ', v)

但我无法在 ansible 的 jinja2 模板中创建它。我还没有找到 ljust 的替代品。

目前我的模板是这样的,但是我得到了一个没有格式的输出。

{% for key, value in data['_dictionary'].items() %}
    {{ "%s\t%s" | format( key, value ) }}
{% endfor %}

有什么想法和建议吗?

【问题讨论】:

    标签: ansible jinja2 ansible-template


    【解决方案1】:

    例如

        - debug:
            msg: |
              {% for k,v in data['_dictionary'].items() %}
              {{ "{:<15} {}".format(k, v) }}
              {% endfor %}
    

    给予

      msg: |-
        keyone          abc
        rtv 4           data2
        longtexthere    1
        keythree        data3
        keyfour         data1234
    

    参见formatFormat String Syntax


    问:动态创建格式。

    A:例如,查找字典中最长的键。在第一列的长度上再增加 1 个空格。同理,计算第二列的长度,并在单独的变量中创建格式字符串

        - debug:
            msg: |
              {% for k,v in data['_dictionary'].items() %}
              {{ fmt.format(k, v) }} # comment
              {% endfor %}
          vars:
            col1: "{{ data._dictionary.keys()|map('length')|max + 1 }}"
            col2: "{{ data._dictionary.values()|map('length')|max + 1 }}"
            fmt: "{:<{{ col1 }}} {:<{{ col2 }}}"
    

    给予

      msg: |-
        keyone        abc       # comment
        rtv 4         data2     # comment
        longtexthere  1         # comment
        keythree      data3     # comment
        keyfour       data1234  # comment
    

    【讨论】:

    • 很好,可以,但是有什么方法可以动态放置值?我的意思是在 15 个字符中应该是一个变量,但我还没有找到将变量放在那里的方法。
    • 我更新了答案。
    【解决方案2】:

    正在工作,最后我的 j2 文件是:

    {% set col1 = data._dictionary.keys()|map('length')|max %}
    {% set fmt = "{:<" + col1|string + "}    {}" %}
    {% for key, value in data._dictionary.items() %}
        {{ fmt.format(key, value) }}
    {% endfor %}
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多