Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 forJinja.
              "{% endfor %}")

Solution 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 stringt1 = Template(str);

Post a Comment for "How Can I Do Line Break In Jinja2 Python?"