Reputation: 17040
Here is my Python code for generating the template
import jinja2
with open('test.j2', 'r') as f:
template_body = f.read()
template = jinja2.Template(template_body)#, trim_blocks=True)
result = template.render(longest=len('staging'),
envs=['devel', 'staging', 'prod'])
print(result)
The idea here is that I want to produce the follwing indented based on the longest string in the list.
devel = 1
staging = 1
prod = 1
I finally came up with a solution:
{% for env in envs -%}
{%- set padding = (longest - env|length + 1)|string %}
{% set f = "%-" + padding + "s" -%}
{{ env }}{{ f | format(' ',)}}= 1
{%- endfor %}
But I am getting
$ python test.py
devel = 1
staging = 1
prod = 1
There is an extra newline at the start of the output. Using Python's debugger, we can see the output:
$ python test.py
> /private/tmp/test.py(11)<module>()
-> print(result)
(Pdb) result
u'\ndevel = 1\nstaging = 1\nprod = 1'
Upvotes: 1
Views: 7927
Reputation: 198438
You are printing a newline before each line by not suppressing the newline at the set
line. On the other hand, you're suppressing a newline at the end in the endfor
line. Thus, you get a newline before each line, but not after each line.
By changing the code like this, you get the reverse:
{% for env in envs -%}
{%- set padding = (longest - env|length + 1)|string -%}
{% set f = "%-" + padding + "s" -%}
{{ env }}{{ f | format(' ',)}}= 1
{% endfor %}
and result
will be
u'devel = 1\nstaging = 1\nprod = 1\n'
Upvotes: 2