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
Provenance
- Commit
7e912c6- Tree
5072fa0- Author
W. Trevor King <wking@tremily.us>- Committer
W. Trevor King <wking@tremily.us>- Parent
21a2010
7 files changed+45 added−6 removed
modified:docs/templates.rst+3 added-1 removed
154 unmodified lines155 In the default configuration, a single trailing newline is stripped if156 present, and whitespace is not further modified by the template engine. Each157 whitespace (spaces, tabs, newlines etc.) is returned unchanged. If the158 application configures Jinja to `trim_blocks` the first newline after a a159-template tag is removed automatically (like in PHP).159+template tag is removed automatically (like in PHP). To keep the160+single trailing newline when it is present, configure Jinja to161+`keep_trailing_newline`.162 163 But you can also strip whitespace in templates by hand. If you put an minus164 sign (``-``) to the start or end of an block (for example a for tag), a165 comment or variable expression you can remove the whitespaces after or before1218 unmodified linesmodified:jinja2/testsuite/lexnparse.py+13 added
80 unmodified lines81 tmpl = env.from_string('1\n2\r\n3\n4\n')82 result = tmpl.render()83 assert result.replace(seq, 'X') == '1X2X3X4'84 85+ 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)98 99 class ParserTestCase(JinjaTestCase):100 101 def test_php_syntax(self):299 unmodified linesmodified:jinja2/defaults.py+1 added
20 unmodified lines21 LINE_STATEMENT_PREFIX = None22 LINE_COMMENT_PREFIX = None23 TRIM_BLOCKS = False24 NEWLINE_SEQUENCE = '\n'25+KEEP_TRAILING_NEWLINE = False26 27 28 # default filters, tests and namespace29 from jinja2.filters import FILTERS as DEFAULT_FILTERS12 unmodified linesmodified:jinja2/environment.py+12 added-2 removed
138 unmodified lines139 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a140 useful default for Linux and OS X systems as well as web141 applications.142 143+ `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.147+148+ .. versionadded:: 2.7149+150 `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 lines231 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 lines263 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_newline268 269 # runtime information270 self.undefined = undefined271 self.optimized = optimized557 unmodified lines829 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 line839 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)846 847 @classmethod848 def from_code(cls, environment, code, globals, uptodate=None):287 unmodified linesmodified:jinja2/ext.py+3 added-1 removed
587 unmodified lines588 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 linesmodified:jinja2/lexer.py+11 added-2 removed
381 unmodified lines382 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] = lexer34 unmodified lines426 # block suffix if trimming is enabled427 block_suffix_re = environment.trim_blocks and '\\n?' or ''428 429 self.newline_sequence = environment.newline_sequence430+ self.keep_trailing_newline = environment.keep_trailing_newline431 432 # global lexing rules433 self.rules = {434 'root': [115 unmodified lines550 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 linesmodified:CHANGES+2 added
11 unmodified lines12 - 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.20 21 Version 2.6265 unmodified lines