lalalatan lalalatan - 7 months ago 106
Python Question

How can I do line break in jinja2 python?

How can I do line break in jinja2 in python?

Below is my code

t1 = Template("{% for i in range(0, a1) %}|{{ mylist1[i] }}{% for j in range(0, (20 - (mylist1[i]|length))) %}{{ space }}{% endfor %}|{{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}{% for j in range(0, (20 - (dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]]|length))) %}{{ space }}{% endfor %}|\n{{ string }}{% endfor %}")


This code will result in:
enter image description here
Since it is horizontally too long, I want to write them in few lines.

However, If I do what I usually do in python like below:

t1 = Template("{% for i in range(0, a1) %}|\
{{ mylist1[i] }}\
{% for j in range(0, (20 - (mylist1[i]|length))) %}\
{{ space }}\
{% endfor %}|\
{{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}\
{% for j in range(0, (20 - (dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]]|length))) %}\
{{ space }}\
{% endfor %}|\n\
{{ string }}\
{% endfor %}")


The result will be
enter image description here

Can anyone help me to solve this?

Thank you.

Answer

Python preserver spaces so you will see them in the results as well.

str = "{% for i in range(0, a1) %}|\"
str += "{{ mylist1[i] }}\"
str += "{% for j in range(0, (20 - (mylist1[i]|length))) %}\"
str += "{{ space }}\"
str += "{% endfor %}|\"
str += "{{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}\"
str += "{% for j in range(0, (20 - (dicts[mylist1[i]]"
str += "[dicts[mylist1[i]].keys()[0]]|length))) %}\"
str += "{{ space }}\"
str += "{% endfor %}|\n\"
str += "{{ string }}\"
str += "{% endfor %}")"

# and then use the generates string
t1 = Template(str);