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

Time:01-03

I have next jinja2 template:

cfg.jinja2:

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

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

And, next python file:

test.py:

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()
print(data)

It shows next result:

$ python3 test.py



resource:
ABC

    ABC

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

CodePudding user response:

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).

  • Related