Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading