如何在Jinja中省略for循环后的空行



我想用j2cli生成以下输出:

// before
function (arg1,
arg2,
arg3)
// after

我尝试了以下模板:

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] -%}
{{param}}{{"," if not loop.last else ")"}}
{% endfor %}
// after

但它总是在最后产生一条额外的空线:

// before
function (arg1,
arg2,
arg3)

// after

当我尝试这个模板:

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] -%}
{{param}}{{"," if not loop.last else ")"}}
{% endfor -%}
// after

注释缩进。

// before
function (arg1,
arg2,
arg3)
// after

这个

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] %}
{{param}}{{"," if not loop.last else ")"}}
{%- endfor %}
// after

删除末尾的空行,但在开头生成一行。

// before
function (
arg1,
arg2,
arg3)
// after

这个

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] -%}
{{param}}{{"," if not loop.last else ")"}}
{%- endfor %}
// after

删除所有空白。

// before
function (arg1,arg2,arg3)
// after

如何正确格式化函数?

我明白了:(有时它有助于一夜睡眠(

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] -%}
{{param}}{% if not loop.last %},
{% endif %}
{%- endfor %})
// after

Jinja的默认for循环在这里没有帮助,因为它以相同的方式格式化每一行。无论是在每个循环的开头还是结尾,它都保持换行+缩进的组合。但是在第一行之前和最后一行之后换行+缩进是不需要的。行的格式不能统一。

因此,解决方案是禁用for循环{% for -%}...{%- endfor %}的默认空白处理,并在除最后一行之外的每一行之后手动生成换行+缩进。

这可能是通过将CCD_ 4与CCD_。endfor-只是防止空白的生成并且吃掉endif之后的空白,但是不吃掉由if的主体生成的空白。

我只有一个使用自定义配置的工作示例:

j2_custom.py:

def j2_environment_params():
""" Extra parameters for the Jinja2 Environment """
# Jinja2 Environment configuration
# http://jinja.pocoo.org/docs/2.10/api/#jinja2.Environment
return dict(
# Remove whitespace around blocks
trim_blocks=True,
lstrip_blocks=True,
)

j2-template.j2:

// before
function ({% for param in ['arg1', 'arg2', 'arg3'] %}
{{"          " if not loop.first else ""}}{{param}}{{"," if not loop.last else ")"}}
{% endfor %}
// after

cli调用:

$ j2 j2-template.j2 --customize j2_custom.py
// before
function (arg1,
arg2,
arg3)
// after

有一个空白控制,您可以通过+-在模板中手动控制lstrip_blockstrim_blocks,但我没有找到它们的工作示例。

最新更新