Difference of writing jinja2 macro in one line V.S. writing macro in multiple lines?


I have next jinja2 template:


{% macro cfg() %}ABC{% endmacro %}
{% macro cfg2() %}
{% endmacro %}

{{ cfg()|indent(4) }}
{{ cfg2()|indent(4) }}

And, next python file:


import os
from jinja2 import Environment, FileSystemLoader

path_dir = "."
loader = FileSystemLoader(searchpath=path_dir)
env = Environment(loader=loader)
template = env.get_template("cfg.jinja2")
data = template.render()

It shows next result:

$ python3 test.py



I wonder, why cfg() has no effect with indent filter while cfg2() works as expected?

>Solution :

From indent docs:

Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.

cfg() returns a single line: "ABC". The first line is not indented.

cfg2() returns three lines, first and last of which are empty: "\nABC\n". The empty lines not being indented, the result has the second line indented: "\n ABC\n".

The reason cfg() and cfg2() have different outputs is because cfg2 has two newlines in its definition: "{% macro cfg2() %}\nABC\n{% endmacro %}".

You could force your first example to also indent: {{ cfg()|indent(4, first=True) }}; it will result in output similar, but not identical to that of cfg2(): " ABC" (but without the two newlines).

Leave a Reply Cancel reply