Jinja: Trailing newline is stripped from template when rendering.

Created on 2 May 2018  ·  2Comments  ·  Source: pallets/jinja

Expected Behavior

When rendering a file that ends in a newline (\n) character, I would expect that the rendered output would also end in a newline character. It is a standard convention on UNIX-like systems to end text files with a trailing newline.

Actual Behavior

The final newline is stripped from the rendered output.

Example

>>> c
u'foo is {{ foo }}\nquux is {{ quux }}\nasdf\n'
>>> t = jinja2.Template(c)
>>> t.render(foo="bar", quux="baz")
u'foo is bar\nquux is baz\nasdf'
>>> s = t.stream()
>>> s.next()
u'foo is \nquux is \nasdf'
>>> s.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ifreeman/.local/lib/python2.7/site-packages/jinja2/environment.py", line 1271, in __next__
    return self._next()
StopIteration
>>>

Your Environment

  • Python version: 2.7.14+ (Debian buster/testing)
  • Jinja version: 2.10 (via pip)

Most helpful comment

Ok, thanks for the response, I wasn't aware that was an option, but it seems like this should be the default. It seems odd to assume the user wants to modify the input in unexpected ways that have nothing to do with the template language. In fact, the reason I'm even opening this issue is because I'm using shinto-cli (https://github.com/istrategylabs/shinto-cli) to parameterize some files in a build job, and I noticed that it was outputting files without newlines, so when I append to them I have lines squished together on one line. At first I was going to open an issue with shinto-cli until I glanced through the source, and then tried a basic jinja2 template from the python REPL myself and realized this is just default jinja2 behavior.

I can open an issue with shinto-cli to ask that they add the keep_trailing_newline=True option to all of their Environment calls.

All 2 comments

Pass keep_trailing_newline=True to the Environment: http://jinja.pocoo.org/docs/api/#jinja2.Environment

Ok, thanks for the response, I wasn't aware that was an option, but it seems like this should be the default. It seems odd to assume the user wants to modify the input in unexpected ways that have nothing to do with the template language. In fact, the reason I'm even opening this issue is because I'm using shinto-cli (https://github.com/istrategylabs/shinto-cli) to parameterize some files in a build job, and I noticed that it was outputting files without newlines, so when I append to them I have lines squished together on one line. At first I was going to open an issue with shinto-cli until I glanced through the source, and then tried a basic jinja2 template from the python REPL myself and realized this is just default jinja2 behavior.

I can open an issue with shinto-cli to ask that they add the keep_trailing_newline=True option to all of their Environment calls.

Was this page helpful?
0 / 5 - 0 ratings