【问题标题】:How to omit an empty line after a for loop in Jinja?如何在 Jinja 的 for 循环后省略空行?
【发布时间】:2020-09-08 15:34:06
【问题描述】:

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

如何正确格式化函数?

【问题讨论】:

    标签: jinja2 jinja2-cli


    【解决方案1】:

    我只有 custom config 的工作示例:

    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
    

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      这可能是通过将endif{{param}} 对齐在同一列中。 endfor- 只是防止产生空白并吃掉endif 之后的空白,但不会吃掉if 的主体产生的空白。

      【讨论】:

        猜你喜欢
        • 2018-05-21
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        • 2019-04-19
        • 2020-08-26
        • 2012-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多