换行和破折号在jinja中无法正常工作

new*_*ike 4 python jinja2 python-2.7

我怎样才能产生预期的输出?谢谢

jinja模板

{%- for field in fields -%}

-
  name: {{field}}
  type: string



{%- endfor -%}
Run Code Online (Sandbox Code Playgroud)

产量

-
  name: operating revenue
  type: string-
  name: gross operating profit
  type: string-
Run Code Online (Sandbox Code Playgroud)

预期产出

-
  name: operating revenue
  type: string
-
  name: gross operating profit
  type: string
Run Code Online (Sandbox Code Playgroud)

from jinja2 import Template

fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"]
template_file = open('./fields_template.jinja2').read()
template = Template(template_file)
html_rendered = template.render(fields=fields)
print(html_rendered)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

-删除之间的所有空格那边的神社的标签和第一个字符.您正在使用-标签的"内部",因此空白被移除到-角色之后,在单词之后string,将两者连接起来.删除其中一个.

例如,您可以删除文本开头和结尾的额外换行符,并-从开始标记的内侧删除:

{%- for field in fields %}
-
  name: {{field}}
  type: string
{%- endfor -%}
Run Code Online (Sandbox Code Playgroud)

演示:

>>> from jinja2 import Template
>>> fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"]
>>> template_file = '''\
... {%- for field in fields %}
... -
...   name: {{field}}
...   type: string
... {%- endfor -%}
... '''
>>> template = Template(template_file)
>>> html_rendered = template.render(fields=fields)
>>> print(html_rendered)

-
  name: operating revenue
  type: string
-
  name: gross operating profit
  type: string
-
  name: EBITDA
  type: string
-
  name: operating profit after depreciation
  type: string
-
  name: EBIT
  type: string
-
  name: date
  type: string
Run Code Online (Sandbox Code Playgroud)