benbenben
benbenben

Reputation: 159

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.

Upvotes: 3

Views: 31286

Answers (2)

WloHu
WloHu

Reputation: 1527

You shouldn't use string concatenation like in this answer. In your case take advantage of parentheses and implicit string concatenation.

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

Upvotes: 5

CodeWizard
CodeWizard

Reputation: 142352

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);

Upvotes: 1

Related Questions