换行符和破折号在神社中无法正常工作

newline and dash not working correctly in jinja

如何生成预期的输出?谢谢

jinja 模板

{%- for field in fields -%}

-
  name: {{field}}
  type: string



{%- endfor -%}

产出

-
  name: operating revenue
  type: string-
  name: gross operating profit
  type: string-

预期输出

-
  name: operating revenue
  type: string
-
  name: gross operating profit
  type: string

代码

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)

- 删除 Jinja 标签的 that side 和第一个字符之间的所有空格。您在标签的 'inside' 上使用了 -,因此删除了 - 字符和单词 string 之后的空格,将两者连接起来。删除一个或另一个。

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

{%- for field in fields %}
-
  name: {{field}}
  type: string
{%- endfor -%}

演示:

>>> 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

您可以抑制以下行的呈现:

<% for ... %>
<% endfor %>
<% if ... %>
<% endif %>

根据 their docs 在您的 jinja2 环境中设置 trim_blocks=True 和 lstrip_blocks=True。请参阅下面的更新代码:

from jinja2 import Template

fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"]
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'), trim_blocks=True, lstrip_blocks=True)

html_rendered = jinja_env.get_template('fields_template.jinja2').render(fields=fields)
print(html_rendered)

将您的模板文件编辑为(直观):

{% for field in fields %}
-
  name: {{field}}
  type: string
{% endfor %}