newline and dash not working correctly in jinja

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-19 07:53:43

问题


How could I generate the expected output ? Thanks

jinja template

{%- for field in fields -%}

-
  name: {{field}}
  type: string



{%- endfor -%}

output

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

expected output

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

code

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)

回答1:


The - removes all whitespace between that side of the Jinja tag and the first character. You are using - on the 'inside' of the tags, so whitespace is removed up to the - character and after the word string, joining up the two. Remove one or the other.

You could remove the extra newlines at the start and end of your text for example, and remove the - from the inside side of the opening tag:

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

Demo:

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


You can suppress rendering of the below lines:

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

by setting trim_blocks=True and lstrip_blocks=True in your jinja2 environment per their docs. See your updated code below:

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)

Edit your template file to be (the intuitive):

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


来源:https://stackoverflow.com/questions/33232830/newline-and-dash-not-working-correctly-in-jinja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!