0

我想用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

如何正确格式化函数?

4

2 回答 2

1

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

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

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

于 2020-09-08T20:58:20.763 回答
1

我明白了:(有时它有助于睡一晚)

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

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

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

这可能是通过将 与 对齐endif在同一列中{{param}}。的只是阻止了空格的产生并吃掉了之后的空格,-但不吃掉了 的主体产生的空格。endforendifif

于 2020-09-09T08:26:22.803 回答