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

标签 python python-2.7 yaml jinja2 removing-whitespace

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

神社模板

{%- 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 标签的那一侧和第一个字符之间的所有空格。您在标签的“内部”使用 -,因此删除了 - 字符和单词 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

关于python - 换行符和破折号在神社中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232830/

相关文章:

python - Webiopi (Raspberry pi) 与 sql 或 sqlite

python - 如何使用 python 检索远程主机的 TLS/SSL 对等证书?

python - Django Rest Framework 中模型方法中的业务逻辑在哪里?

python - 过滤 Pandas 中特定日期范围的数据框

python-2.7 - Windows 64位上的Python 32位Ctypes模块错误

yaml - 在 YAML 文件中插入变量/常量

linux - 如何将脚本的输出保存在ansible 2.0.2文件中

python - 如何使用pandas从dataframe中获取数据

python - 如果我在 Chrome 选项中指定 user-data-dir,Selenium chromedriver 会挂起

python - 为静态文件配置 Python GAE app.yaml