dorancemc
dorancemc

Reputation: 163

padding/ljust with ansible template and jinja

I am looking for a way to create a template in ansible with this dictionary.

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

The template output should have this format:

 keyone          abc
 keytwo          data2
 longtexthere    1
 keythree        data3
 keyfour         data1234

With python I can create it with:

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

But I can't a way to create it in a jinja2 template in ansible. I have not found a replacement for ljust.

Currently my template is this, but I got a output without format.

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

Any ideas, sugestion?

Upvotes: 3

Views: 2058

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68179

For example,

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

gives

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

See format and Format String Syntax.


Q: "Create the format dynamically."

A: For example, find the longest key in the dictionary. Add 1 more space to the length of the first column. In the same way, calculate the length of the second column and create the format string in a separate variable

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

gives

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

Upvotes: 3

dorancemc
dorancemc

Reputation: 163

Is working, at the end my j2 file is:

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

Thank you.

Upvotes: 0

Related Questions