How do you control whitespace in Jinja2 templates?
IntermediateConceptJinja2, Conditionals and Loops
Answer
Statement tags leave blank lines and indentation behind. Control it with:
{%- ... -%}— a dash trims whitespace on that sidetrim_blocks(defaulttruein thetemplatemodule) removes the first newline after a block taglstrip_blocks: truestrips leading spaces before a block tag
- ansible.builtin.template:
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
lstrip_blocks: true
Check output with --diff, and watch for YAML or Python-style files where indentation matters.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner