Trimming blocks using whitespace control from jinja2 template

北城余情 提交于 2019-12-24 02:12:14

问题


I'm trying to print a single blank line surrounding the results of a jinja2 for loop, but I just can't get it to work. Can someone tell me what I am doing wrong?

from jinja2 import Template, Environment

template = Template("""This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}

This is some text that should have a single blank line above it.""")

template.environment = Environment(trim_blocks=True)

print(template.render())

This is the result I get:

This is some text that should have a single blank line below it.

line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9


This is some text that should have a single blank line above it.

However, I'm trying to configure it so that I don't get two blank lines above the final line, only one.


回答1:


Ah, I worked it out. I was using the environment incorrectly. From the docs:

Instances of this class [Environment] may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

The correct code is below

from jinja2 import Environment

template_string = """This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}

This is some text that should have a single blank line above it."""

env = Environment(trim_blocks=True)

template = env.from_string(template_string)

print(template.render())

and the result:

This is some text that should have a single blank line below it.

line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9

This is some text that should have a single blank line above it.



回答2:


line {{ i }} prints text followed by a newline, then you have an empty lines which makes it two. Simply remove an empty line:

template = Template("""This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}
This is some text that should have a single blank line above it."""


来源:https://stackoverflow.com/questions/35956589/trimming-blocks-using-whitespace-control-from-jinja2-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!