Lior
Lior

Reputation: 35

Avoid indentation on a newline after a set of if+for in a Jinja2 template

So I have this template:

array (
  {% if dict is defined %}
  {% for key, value in dict.items() %}
  '{{ key }}' => {{ value }},
  {% endfor %}
  {% endif %}
),

I know I need to attach a dash sign to some of the {% / %} characters but I just can't find the right combination. Here's the expected result:

array (
  'key1' => value1,
  'key2' => value2,
  ...
),

So far this is the closest combination to what I want:

array (
  {% if dict is defined -%}
  {% for key, value in dict.items() -%}
  '{{ key }}' => {{ value }},
  {% endfor -%}
  {% endif -%}
),

result:

array (
  'key1' => value1,
  'key2' => value2,
  ...
  'keyN' => valueN,
  ), <- this should not be indented

Note that I tried the solution mentioned in this similar case: Python jinja2 indentention and whitespace issue

But it doesn't work for me either, resulting in the whole output being written on the same line.

I tried many more combinations but none of them works so far, most of them result in all kay-value pairs being written on the same line. Is there anyone in the crowd who is more experienced with Jinja and knows how to get it right?

Upvotes: 2

Views: 1867

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39069

In order to achieve this, you will also have to use the Jinja2 trim_blocks environment parameter.

It is here demonstrated in a debug task but the same comment line can, of course, be added at the beginning of any *.j2 file treated by the template module.

So the magic comment line is this one:

#jinja2: trim_blocks:False

Also note that, in order to reduce the complexity of the two blocks to control whitespace on, I am using the for ... if construct.

And so given the playbook:

- hosts: all
  gather_facts: no

  tasks:
    - debug:
        msg: |
          #jinja2: trim_blocks:False
          array (
            {%- for key, value in dict.items() if dict is defined %}
            '{{ key }}' => {{ value }},
            {%- endfor %}
          ),
      vars:
        dict: 
          lorem: ipsum
          dolor: sit

This gives the output:

TASK [debug] *************************************************************
ok: [localhost] => {
    "msg": "array (\n  'lorem' => ipsum,\n  'dolor' => sit,\n),\n"
}  

Upvotes: 1

Related Questions