Skip to content
Myr

Add `keep_trailing_newline` to configure final endline stripping

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This option defaults to False for compatibility with the existing behaviour. I've added the option because I expect I won't remember to keep an extra trailing newline in my templates, and some non-HTML templates *need* that last newline. See also: https://groups.google.com/d/msg/pocoo-libs/6DylMqq1voI/GXTbZJ1Tr-sJ

authored by W. Trevor King · committed by W. Trevor King · parent 21a2010 · Browse files · 7 files+45 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+45 added−6 removed

  • other:+45 added−6 removed

7 files+45 added−6 removed

modified:docs/templates.rst+3 added-1 removed
154 unmodified lines
155In the default configuration, a single trailing newline is stripped if156present, and whitespace is not further modified by the template engine. Each157whitespace (spaces, tabs, newlines etc.) is returned unchanged. If the158application configures Jinja to `trim_blocks` the first newline after a a159template tag is removed automatically (like in PHP).159template tag is removed automatically (like in PHP). To keep the160single trailing newline when it is present, configure Jinja to161`keep_trailing_newline`.162163But you can also strip whitespace in templates by hand. If you put an minus164sign (``-``) to the start or end of an block (for example a for tag), a165comment or variable expression you can remove the whitespaces after or before
1218 unmodified lines
modified:jinja2/testsuite/lexnparse.py+13 added
80 unmodified lines
81 tmpl = env.from_string('1\n2\r\n3\n4\n')82 result = tmpl.render()83 assert result.replace(seq, 'X') == '1X2X3X4'8485 def test_trailing_newline(self):86 for keep in [True, False]:87 env = Environment(keep_trailing_newline=keep)88 for template,expected in [89 ('', {}),90 ('no\nnewline', {}),91 ('with\nnewline\n', {False: 'with\nnewline'}),92 ('with\nseveral\n\n\n', {False: 'with\nseveral\n\n'}),93 ]:94 tmpl = env.from_string(template)95 expect = expected.get(keep, template)96 result = tmpl.render()97 assert result == expect, (keep, template, result, expect)9899class ParserTestCase(JinjaTestCase):100101 def test_php_syntax(self):
299 unmodified lines
modified:jinja2/defaults.py+1 added
20 unmodified lines
21LINE_STATEMENT_PREFIX = None22LINE_COMMENT_PREFIX = None23TRIM_BLOCKS = False24NEWLINE_SEQUENCE = '\n'25KEEP_TRAILING_NEWLINE = False262728# default filters, tests and namespace29from jinja2.filters import FILTERS as DEFAULT_FILTERS
12 unmodified lines
modified:jinja2/environment.py+12 added-2 removed
138 unmodified lines
139 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a140 useful default for Linux and OS X systems as well as web141 applications.142143 `keep_trailing_newline`144 Preserve the trailing newline when rendering templates.145 The default is ``False``, which causes a single newline,146 if present, to be stripped from the end of the template.147148 .. versionadded:: 2.7149150 `extensions`151 List of Jinja extensions to use. This can either be import paths152 as strings or extension classes. For more information have a153 look at :ref:`the extensions documentation <jinja-extensions>`.
77 unmodified lines
231 line_statement_prefix=LINE_STATEMENT_PREFIX,232 line_comment_prefix=LINE_COMMENT_PREFIX,233 trim_blocks=TRIM_BLOCKS,234 newline_sequence=NEWLINE_SEQUENCE,235 keep_trailing_newline=KEEP_TRAILING_NEWLINE,236 extensions=(),237 optimized=True,238 undefined=Undefined,239 finalize=None,
23 unmodified lines
263 self.line_statement_prefix = line_statement_prefix264 self.line_comment_prefix = line_comment_prefix265 self.trim_blocks = trim_blocks266 self.newline_sequence = newline_sequence267 self.keep_trailing_newline = keep_trailing_newline268269 # runtime information270 self.undefined = undefined271 self.optimized = optimized
557 unmodified lines
829 line_statement_prefix=LINE_STATEMENT_PREFIX,830 line_comment_prefix=LINE_COMMENT_PREFIX,831 trim_blocks=TRIM_BLOCKS,832 newline_sequence=NEWLINE_SEQUENCE,833 keep_trailing_newline=KEEP_TRAILING_NEWLINE,834 extensions=(),835 optimized=True,836 undefined=Undefined,837 finalize=None,
1 unmodified line
839 env = get_spontaneous_environment(840 block_start_string, block_end_string, variable_start_string,841 variable_end_string, comment_start_string, comment_end_string,842 line_statement_prefix, line_comment_prefix, trim_blocks,833 newline_sequence, frozenset(extensions), optimized, undefined,834 finalize, autoescape, None, 0, False, None)843 newline_sequence, keep_trailing_newline, frozenset(extensions),844 optimized, undefined, finalize, autoescape, None, 0, False, None)845 return env.from_string(source, template_class=cls)846847 @classmethod848 def from_code(cls, environment, code, globals, uptodate=None):
287 unmodified lines
modified:jinja2/ext.py+3 added-1 removed
587 unmodified lines
588 options.get('comment_end_string', COMMENT_END_STRING),589 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,590 options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,591 getbool(options, 'trim_blocks', TRIM_BLOCKS),592 NEWLINE_SEQUENCE, frozenset(extensions),592 NEWLINE_SEQUENCE,593 getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),594 frozenset(extensions),595 cache_size=0,596 auto_reload=False597 )598
24 unmodified lines
modified:jinja2/lexer.py+11 added-2 removed
381 unmodified lines
382 environment.comment_end_string,383 environment.line_statement_prefix,384 environment.line_comment_prefix,385 environment.trim_blocks,386 environment.newline_sequence)386 environment.newline_sequence,387 environment.keep_trailing_newline)388 lexer = _lexer_cache.get(key)389 if lexer is None:390 lexer = Lexer(environment)391 _lexer_cache[key] = lexer
34 unmodified lines
426 # block suffix if trimming is enabled427 block_suffix_re = environment.trim_blocks and '\\n?' or ''428429 self.newline_sequence = environment.newline_sequence430 self.keep_trailing_newline = environment.keep_trailing_newline431432 # global lexing rules433 self.rules = {434 'root': [
115 unmodified lines
550 def tokeniter(self, source, name, filename=None, state=None):551 """This method tokenizes the text and returns the tokens in a552 generator. Use this method if you just want to tokenize a template.553 """552 source = '\n'.join(unicode(source).splitlines())554 source = unicode(source)555 lines = source.splitlines()556 if self.keep_trailing_newline and source:557 for newline in ('\r\n', '\r', '\n'):558 if source.endswith(newline):559 lines.append('')560 break561 source = '\n'.join(lines)562 pos = 0563 lineno = 1564 stack = ['root']565 if state is not None and state != 'root':
125 unmodified lines
modified:CHANGES+2 added
11 unmodified lines
12- Added a non-silent option for babel extraction.13- Added `urlencode` filter that automatically quotes values for14 URL safe usage with utf-8 as only supported encoding. If applications15 want to change this encoding they can override the filter.16- Added `keep-trailing-newline` configuration to environments and17 templates to optionally preserve the final trailing newline.18- Accessing `last` on the loop context no longer causes the iterator19 to be consumed into a list.2021Version 2.6
265 unmodified lines