[英]Difference of writing jinja2 macro in one line V.S. writing macro in multiple lines?
I have next jinja2 template:我有下一个 jinja2 模板:
cfg.jinja2: cfg.jinja2:
{% macro cfg() %}ABC{% endmacro %}
{% macro cfg2() %}
ABC
{% endmacro %}
resource:
{{ cfg()|indent(4) }}
{{ cfg2()|indent(4) }}
And, next python file:然后,下一个 python 文件:
test.py:测试.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?我想知道,为什么
cfg()
对indent filter
没有影响,而cfg2()
按预期工作?
From indent
docs :从
indent
文档:
Return a copy of the string with each line indented by 4 spaces.
返回字符串的副本,每行缩进 4 个空格。 The first line and blank lines are not indented by default.
默认情况下,首行和空行不缩进。
cfg()
returns a single line: "ABC"
. cfg()
返回一行: "ABC"
。 The first line is not indented.第一行没有缩进。
cfg2()
returns three lines, first and last of which are empty: "\nABC\n"
. cfg2()
返回三行,第一行和最后一行为空: "\nABC\n"
。 The empty lines not being indented, the result has the second line indented: "\n ABC\n"
.空行未缩进,结果缩进了第二行:
"\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 %}"
. cfg()
和cfg2()
具有不同输出的原因是因为cfg2
在其定义中有两个换行符: "{% macro cfg2() %}\nABC\n{% endmacro %}"
。
You could force your first example to also indent: {{ cfg()|indent(4, first=True) }}
;你可以强制你的第一个例子也缩进:
{{ cfg()|indent(4, first=True) }}
; it will result in output similar, but not identical to that of cfg2()
: " ABC"
(but without the two newlines).它将导致 output 类似于
cfg2()
的结果,但不完全相同: " ABC"
(但没有两个换行符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.