3

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.

benbenben
  • 159
  • 1
  • 3
  • 10

2 Answers2

5

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 %}")
WloHu
  • 1,369
  • 17
  • 24
2

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);
CodeWizard
  • 128,036
  • 21
  • 144
  • 167