Why doesn't a template with {% for %} and {% endfor %} on their own lines leave blank lines in the output when Ansible renders it?
Ansible's template module enables Jinja2's trim_blocks by default, which removes the newline right after a block tag; plain Jinja2 would leave an empty line for each tag.
Every character outside the tags is output, including the line break that ends the {% for ... %} line. Rendered with plain Jinja2 defaults, the users loop from the previous card gives:
User number 1 - alice
User number 2 - bob
The template module sets trim_blocks: true, so the newline after {% ... %} is dropped and the output is just the two lines. (Checked by rendering both ways with Jinja2 3.1.)
Two related controls:
lstrip_blocks: true(module option, off by default) also removes spaces and tabs before a block tag, so you can indent tags to match the file's structure.- A minus sign inside a tag strips whitespace on that side manually, for example
{%- if x %}or{{ value -}}.
This only concerns block tags {% %}; the newline after a {{ }} expression is kept.
Go deeper:
ansible.builtin.template: trim_blocks (official docs) — the default and
lstrip_blocks.Template Designer Documentation: whitespace control (Jinja) —
trim_blocks,lstrip_blocksand the minus syntax.