【问题标题】:newline and dash not working correctly in jinja换行符和破折号在 jinja 中无法正常工作
【发布时间】:2016-01-18 21:17:21
【问题描述】:

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

神社模板

{%- 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)

【问题讨论】:

标签: python python-2.7 yaml jinja2 removing-whitespace


【解决方案1】:

- 删除了 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

【讨论】:

    【解决方案2】:

    您可以禁止渲染以下行:

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

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2020-10-08
      • 2014-08-06
      • 2023-03-20
      • 2016-12-11
      • 1970-01-01
      相关资源
      最近更新 更多