jeremy
jeremy

Reputation: 4681

Trimming blocks using whitespace control from jinja2 template

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.

Upvotes: 2

Views: 8638

Answers (2)

jeremy
jeremy

Reputation: 4681

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.

Upvotes: 2

Zibi
Zibi

Reputation: 350

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."""

Upvotes: 1

Related Questions