Newline And Dash Not Working Correctly In Jinja
How could I generate the expected output ? Thanks jinja template {%- for field in fields -%} - name: {{field}} type: string {%- endfor -%} output - name: operating reven
Solution 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
Solution 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 %}
Post a Comment for "Newline And Dash Not Working Correctly In Jinja"