jinja2如何删除尾随换行符

jinja2如何删除尾随换行符

本文介绍了jinja2如何删除尾随换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jinja 2输出yaml文件,但似乎无法摆脱尾随的换行符和for循环的结尾.例如下面的

I'm using jinja 2 to output a yaml file but can't seem to get rid of a trailing newline and the end of a for loop. Eg the below

 - request:
        path: {{ path }}
        headers:
          origin: 'somedomain.com'
          user-agent: 'agent'
          referer: 'some.domain.com'
          authority: 'somedomain.com'
        querystring:
          {% for key, value in querystring.items() -%}
          {{ key }}: '{{ value }}'
          {% endfor %}
      response:
        content:
          file: {{ content }}

给我输出:

- request:
    path: /some/path
    headers:
      origin: 'somedomain.com'
      user-agent: 'agent'
      referer: 'somedomain.com'
      authority: 'somedomain.com'
    querystring:
      postcode: 'xxxxxx'
      houseNo: '55'

  response:
    content:
      file: address.json

在门牌号后附加一个多余的空白行.我如何摆脱这一行?

With an additional unwanted blank line after houseNo. How do I get rid of this line?

推荐答案

更改您的循环以从输出的顶部和底部去除空格(请注意,在for循环关闭处应加上额外的-"):

Change your loop to strip white spaces from the top AND bottom of the output (notice extra "-" at the for loop close):

 {% for key, value in querystring.items() -%}
      {{ key }}: '{{ value }}'
 {%- endfor %}

在我的测试中(使用 https://github.com/abourguignon/jinja2-live-parser ),-"必须在第一个{%之后,而不是在最后一个之前,以实现您的要求.

In my tests (using https://github.com/abourguignon/jinja2-live-parser), the "-" must come after the first {%, not before the last to achieve what you're asking for.

文档: http://jinja.pocoo.org/docs/dev /templates/#whitespace-control

这篇关于jinja2如何删除尾随换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:48