2

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.

jeremy
  • 4,421
  • 4
  • 23
  • 27

2 Answers2

2

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.
GammaGames
  • 1,617
  • 1
  • 17
  • 32
jeremy
  • 4,421
  • 4
  • 23
  • 27
1

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."""
Zibi
  • 350
  • 1
  • 13
  • sorry, this is not really what I was looking for, because I wanted to trim the blocks and that wasn't working. But thanks for your help anyway! :) – jeremy Mar 12 '16 at 10:58