When writing a for / if statement with the jinja2 template, the way line breaks are made depends on the presence or absence of hyphens and their positions. I always get lost when writing a for statement, so I will summarize it. How do I write to get the following output?
output
start
apple0
orange0
apple1
orange1
end
The following template will be the standard for this time. Put hyphens before and after the start position and end position of the for statement.
jinja_test1.j2
start
{%- for i in range(2) -%}
apple{{ i }}
orange{{ i }}
{%- endfor -%}
end
There is a line break only between apple and orange. It seems that the content written in the for statement will break the line without permission.
output
startapple0
orange0apple1
orange1end
jinja_test2.j2
start
{% for i in range(2) -%}
apple{{ i }}
orange{{ i }}
{%- endfor -%}
end
There was a line break between start and apple0. Before the start position of the for statement, a line break occurs only once at the start of the for statement.
output
start
apple0
orange0apple1
orange1end
jinja_test3.j2
start
{%- for i in range(2) %}
apple{{ i }}
orange{{ i }}
{%- endfor -%}
end
There is a line break before apple0 and apple1. After the start position of the for statement, a line break occurs every time at the start position in the for statement.
output
start
apple0
orange0
apple1
orange1end
jinja_test4.j2
start
{%- for i in range(2) -%}
apple{{ i }}
orange{{ i }}
{% endfor -%}
end
Line breaks are now added after orange0 and orange1. Before the end position of the for statement, a line break occurs every time on the last line in the for statement.
output
startapple0
orange0
apple1
orange1
end
jinja_test5.j2
start
{%- for i in range(2) -%}
apple{{ i }}
orange{{ i }}
{%- endfor %}
end
A line break is now added after orange1. After the end position of the for statement, it seems that a line break occurs only once when leaving the for statement.
output
startapple0
orange0apple1
orange1
end
Based on the contents so far, it is as follows.
Position to erase hyphens | How to break a line |
---|---|
Before the for statement start position | Only one line break at the beginning of the for statement |
behind the for statement start position | Newline every time at the beginning of the loop |
Before the end position of the for statement | Newline every time at the end of the loop |
Behind the end position of the for statement | One line break at the end of the for statement |
That is, to get the first output ・ Two line breaks between start and apple0 → No need for hyphens before and after the for statement start position -It is necessary to break twice between orange1 and end → No need for hyphens before and after the end position of the for statement So, "Erase all hyphens" is the correct answer, and it is as follows.
jinja_test6.j2
start
{% for i in range(2) %}
apple{{ i }}
orange{{ i }}
{% endfor %}
end
output
start
apple0
orange0
apple1
orange1
end
Recommended Posts