newline and dash not working correctly in jinja
Asked Answered
S

2

9

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)
Segura answered 20/10, 2015 at 9:25 Comment(1)
THanks your solution still not working for me, please check it gist.github.com/poc7667/717bb260ed959184cdbfSegura
G
14

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
Graticule answered 20/10, 2015 at 9:27 Comment(0)
I
0

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 %}
Ignominy answered 10/4, 2018 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.