我怎样才能产生预期的输出?感谢
{%- 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)
答案 0 :(得分:6)
-
删除Jinja标记的那边与第一个字符之间的所有空格。您在代码的“内部”使用了-
,因此空白被移除到-
字符,并在单词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
答案 1 :(得分:0)
您可以禁止渲染以下行:
<% 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 %}