Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trailing newline is stripped from template when rendering. #848

Closed
memotype opened this issue May 2, 2018 · 2 comments
Closed

Trailing newline is stripped from template when rendering. #848

memotype opened this issue May 2, 2018 · 2 comments

Comments

@memotype
Copy link

memotype commented May 2, 2018

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)
@davidism
Copy link
Member

davidism commented May 2, 2018

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

@davidism davidism closed this as completed May 2, 2018
@memotype
Copy link
Author

memotype commented May 3, 2018

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants