Skip to content
Myr

Merge remote-tracking branch 'kristi/master'

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

authored by Armin Ronacher · committed by Armin Ronacher · parents 0a6f850, e4a74f9 · Browse files · 7 files+270 added−13 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+270 added−13 removed

  • other:+270 added−13 removed

7 files+270 added−13 removed

modified:docs/templates.rst+43 added-5 removed
153 unmodified lines
154155In 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). To keep the160single trailing newline when it is present, configure Jinja to161`keep_trailing_newline`.158application configures Jinja to `trim_blocks` the first newline after a159template tag is removed automatically (like in PHP). The `lstrip_blocks`160option can also be set to strip tabs and spaces from the beginning of161line to the start of a block. (Nothing will be stripped if there are162other characters before the start of the block.)163164With both `trim_blocks` and `lstrip_blocks` enabled you can put block tags165on their own lines, and the entire block line will be removed when166rendered, preserving the whitespace of the contents. For example,167without the `trim_blocks` and `lstrip_blocks` options, this template::168169 <div>170 {% if True %}171 yay172 {% endif %}173 </div>174175gets rendered with blank lines inside the div::176177 <div>178 179 yay180 181 </div>182183But with both `trim_blocks` and `lstrip_blocks` enabled, the lines with the 184template blocks are removed while preserving the whitespace of the contents::185 186 <div>187 yay188 </div>189190You can manually disable the `lstrip_blocks` behavior by putting a191plus sign (``+``) at the start of a block::192193 <div>194 {%+ if something %}yay{% endif %}195 </div>196163But you can also strip whitespace in templates by hand. If you put an minus197You can also strip whitespace in templates by hand. If you put an minus198sign (``-``) to the start or end of an block (for example a for tag), a199comment or variable expression you can remove the whitespaces after or before200that block::201
6 unmodified lines
208209If :ref:`line-statements` are enabled they strip leading whitespace210automatically up to the beginning of the line.211212Jinja2 by default also removes trailing newlines. To keep the single213trailing newline when it is present, configure Jinja to214`keep_trailing_newline`.215216.. admonition:: Note217218 You must not use a whitespace between the tag and the minus sign.219
1206 unmodified lines
modified:jinja2/testsuite/lexnparse.py+166 added
416 unmodified lines
417 tmpl = env.from_string('{{ -foo["bar"]|abs }}')418 assert tmpl.render(foo={'bar': 42}) == '42'419420421class LstripBlocksTestCase(JinjaTestCase):422423 def test_lstrip(self):424 env = Environment(lstrip_blocks=True, trim_blocks=False)425 tmpl = env.from_string(''' {% if True %}\n {% endif %}''')426 assert tmpl.render() == "\n"427428 def test_lstrip_trim(self):429 env = Environment(lstrip_blocks=True, trim_blocks=True)430 tmpl = env.from_string(''' {% if True %}\n {% endif %}''')431 assert tmpl.render() == ""432433 def test_no_lstrip(self):434 env = Environment(lstrip_blocks=True, trim_blocks=False)435 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')436 assert tmpl.render() == " \n "437438 def test_lstrip_endline(self):439 env = Environment(lstrip_blocks=True, trim_blocks=False)440 tmpl = env.from_string(''' hello{% if True %}\n goodbye{% endif %}''')441 assert tmpl.render() == " hello\n goodbye"442443 def test_lstrip_inline(self):444 env = Environment(lstrip_blocks=True, trim_blocks=False)445 tmpl = env.from_string(''' {% if True %}hello {% endif %}''')446 assert tmpl.render() == 'hello '447448 def test_lstrip_nested(self):449 env = Environment(lstrip_blocks=True, trim_blocks=False)450 tmpl = env.from_string(''' {% if True %}a {% if True %}b {% endif %}c {% endif %}''')451 assert tmpl.render() == 'a b c '452453 def test_lstrip_left_chars(self):454 env = Environment(lstrip_blocks=True, trim_blocks=False)455 tmpl = env.from_string(''' abc {% if True %}456 hello{% endif %}''')457 assert tmpl.render() == ' abc \n hello'458459 def test_lstrip_embeded_strings(self):460 env = Environment(lstrip_blocks=True, trim_blocks=False)461 tmpl = env.from_string(''' {% set x = " {% str %} " %}{{ x }}''')462 assert tmpl.render() == ' {% str %} '463464 def test_lstrip_preserve_leading_newlines(self):465 env = Environment(lstrip_blocks=True, trim_blocks=False)466 tmpl = env.from_string('''\n\n\n{% set hello = 1 %}''')467 assert tmpl.render() == '\n\n\n'468 469 def test_lstrip_comment(self):470 env = Environment(lstrip_blocks=True, trim_blocks=False)471 tmpl = env.from_string(''' {# if True #}472hello473 {#endif#}''')474 assert tmpl.render() == '\nhello\n'475476 def test_lstrip_angle_bracket_simple(self):477 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',478 lstrip_blocks=True, trim_blocks=True)479 tmpl = env.from_string(''' <% if True %>hello <% endif %>''')480 assert tmpl.render() == 'hello '481482 def test_lstrip_angle_bracket_comment(self):483 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',484 lstrip_blocks=True, trim_blocks=True)485 tmpl = env.from_string(''' <%# if True %>hello <%# endif %>''')486 assert tmpl.render() == 'hello '487488 def test_lstrip_angle_bracket(self):489 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',490 lstrip_blocks=True, trim_blocks=True)491 tmpl = env.from_string('''\492 <%# regular comment %>493 <% for item in seq %>494${item} ## the rest of the stuff495 <% endfor %>''')496 assert tmpl.render(seq=range(5)) == \497 ''.join('%s\n' % x for x in range(5))498 499 def test_lstrip_angle_bracket_compact(self):500 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',501 lstrip_blocks=True, trim_blocks=True)502 tmpl = env.from_string('''\503 <%#regular comment%>504 <%for item in seq%>505${item} ## the rest of the stuff506 <%endfor%>''')507 assert tmpl.render(seq=range(5)) == \508 ''.join('%s\n' % x for x in range(5))509 510 def test_php_syntax_with_manual(self):511 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',512 lstrip_blocks=True, trim_blocks=True)513 tmpl = env.from_string('''\514 <!-- I'm a comment, I'm not interesting -->515 <? for item in seq -?>516 <?= item ?>517 <?- endfor ?>''')518 assert tmpl.render(seq=range(5)) == '01234'519520 def test_php_syntax(self):521 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',522 lstrip_blocks=True, trim_blocks=True)523 tmpl = env.from_string('''\524 <!-- I'm a comment, I'm not interesting -->525 <? for item in seq ?>526 <?= item ?>527 <? endfor ?>''')528 assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))529530 def test_php_syntax_compact(self):531 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',532 lstrip_blocks=True, trim_blocks=True)533 tmpl = env.from_string('''\534 <!-- I'm a comment, I'm not interesting -->535 <?for item in seq?>536 <?=item?>537 <?endfor?>''')538 assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))539540 def test_erb_syntax(self):541 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',542 lstrip_blocks=True, trim_blocks=True)543 #env.from_string('')544 #for n,r in env.lexer.rules.iteritems():545 # print n546 #print env.lexer.rules['root'][0][0].pattern547 #print "'%s'" % tmpl.render(seq=range(5))548 tmpl = env.from_string('''\549<%# I'm a comment, I'm not interesting %>550 <% for item in seq %>551 <%= item %>552 <% endfor %>553''')554 assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))555556 def test_erb_syntax_with_manual(self):557 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',558 lstrip_blocks=True, trim_blocks=True)559 tmpl = env.from_string('''\560<%# I'm a comment, I'm not interesting %>561 <% for item in seq -%>562 <%= item %>563 <%- endfor %>''')564 assert tmpl.render(seq=range(5)) == '01234'565566 def test_erb_syntax_no_lstrip(self):567 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',568 lstrip_blocks=True, trim_blocks=True)569 tmpl = env.from_string('''\570<%# I'm a comment, I'm not interesting %>571 <%+ for item in seq -%>572 <%= item %>573 <%- endfor %>''')574 assert tmpl.render(seq=range(5)) == ' 01234'575576 def test_comment_syntax(self):577 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->',578 lstrip_blocks=True, trim_blocks=True)579 tmpl = env.from_string('''\580<!--# I'm a comment, I'm not interesting -->\581<!-- for item in seq --->582 ${item}583<!--- endfor -->''')584 assert tmpl.render(seq=range(5)) == '01234'585586def suite():587 suite = unittest.TestSuite()588 suite.addTest(unittest.makeSuite(TokenStreamTestCase))589 suite.addTest(unittest.makeSuite(LexerTestCase))590 suite.addTest(unittest.makeSuite(ParserTestCase))591 suite.addTest(unittest.makeSuite(SyntaxTestCase))592 suite.addTest(unittest.makeSuite(LstripBlocksTestCase))593 return suite
modified:jinja2/defaults.py+1 added
20 unmodified lines
21COMMENT_END_STRING = '#}'22LINE_STATEMENT_PREFIX = None23LINE_COMMENT_PREFIX = None24TRIM_BLOCKS = False25LSTRIP_BLOCKS = False26NEWLINE_SEQUENCE = '\n'27KEEP_TRAILING_NEWLINE = False2829
14 unmodified lines
modified:jinja2/environment.py+13 added-4 removed
14 unmodified lines
15 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \16 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \17 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \18 DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \19 KEEP_TRAILING_NEWLINE19 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS20from jinja2.lexer import get_lexer, TokenStream21from jinja2.parser import Parser22from jinja2.optimizer import optimize23from jinja2.compiler import generate
117 unmodified lines
141 `trim_blocks`142 If this is set to ``True`` the first newline after a block is143 removed (block, not variable tag!). Defaults to `False`.144145 `lstrip_blocks`146 If this is set to ``True`` leading spaces and tabs are stripped147 from the start of a line to a block. Defaults to `False`.148149 `newline_sequence`150 The sequence that starts a newline. Must be one of ``'\r'``,151 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a152 useful default for Linux and OS X systems as well as web
89 unmodified lines
242 comment_end_string=COMMENT_END_STRING,243 line_statement_prefix=LINE_STATEMENT_PREFIX,244 line_comment_prefix=LINE_COMMENT_PREFIX,245 trim_blocks=TRIM_BLOCKS,246 lstrip_blocks=LSTRIP_BLOCKS,247 newline_sequence=NEWLINE_SEQUENCE,248 keep_trailing_newline=KEEP_TRAILING_NEWLINE,249 extensions=(),250 optimized=True,
24 unmodified lines
275 self.comment_end_string = comment_end_string276 self.line_statement_prefix = line_statement_prefix277 self.line_comment_prefix = line_comment_prefix278 self.trim_blocks = trim_blocks279 self.lstrip_blocks = lstrip_blocks280 self.newline_sequence = newline_sequence281 self.keep_trailing_newline = keep_trailing_newline282283 # runtime information
38 unmodified lines
322 def overlay(self, block_start_string=missing, block_end_string=missing,323 variable_start_string=missing, variable_end_string=missing,324 comment_start_string=missing, comment_end_string=missing,325 line_statement_prefix=missing, line_comment_prefix=missing,320 trim_blocks=missing, extensions=missing, optimized=missing,326 trim_blocks=missing, lstrip_blocks=missing,327 extensions=missing, optimized=missing,328 undefined=missing, finalize=missing, autoescape=missing,329 loader=missing, cache_size=missing, auto_reload=missing,330 bytecode_cache=missing):331 """Create a new overlay environment that shares all the data with the
511 unmodified lines
843 comment_end_string=COMMENT_END_STRING,844 line_statement_prefix=LINE_STATEMENT_PREFIX,845 line_comment_prefix=LINE_COMMENT_PREFIX,846 trim_blocks=TRIM_BLOCKS,847 lstrip_blocks=LSTRIP_BLOCKS,848 newline_sequence=NEWLINE_SEQUENCE,849 keep_trailing_newline=KEEP_TRAILING_NEWLINE,850 extensions=(),851 optimized=True,
3 unmodified lines
855 env = get_spontaneous_environment(856 block_start_string, block_end_string, variable_start_string,857 variable_end_string, comment_start_string, comment_end_string,858 line_statement_prefix, line_comment_prefix, trim_blocks,851 newline_sequence, keep_trailing_newline, frozenset(extensions),852 optimized, undefined, finalize, autoescape, None, 0, False, None)859 lstrip_blocks, newline_sequence, keep_trailing_newline,860 frozenset(extensions), optimized, undefined, finalize, autoescape,861 None, 0, False, None)862 return env.from_string(source, template_class=cls)863864 @classmethod865 def from_code(cls, environment, code, globals, uptodate=None):
284 unmodified lines
modified:jinja2/ext.py+6 added-1 removed
9 unmodified lines
10 :copyright: (c) 2010 by the Jinja Team.11 :license: BSD.12"""13from jinja2 import nodes14from jinja2.defaults import *14from jinja2.defaults import BLOCK_START_STRING, \15 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \16 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \17 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \18 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS19from jinja2.environment import Environment20from jinja2.runtime import concat21from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError22from jinja2.utils import contextfunction, import_string, Markup
569 unmodified lines
592 options.get('comment_end_string', COMMENT_END_STRING),593 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,594 options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,595 getbool(options, 'trim_blocks', TRIM_BLOCKS),596 getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),597 NEWLINE_SEQUENCE,598 getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),599 frozenset(extensions),600 cache_size=0,
27 unmodified lines
modified:jinja2/lexer.py+40 added-3 removed
389 unmodified lines
390 environment.comment_end_string,391 environment.line_statement_prefix,392 environment.line_comment_prefix,393 environment.trim_blocks,394 environment.lstrip_blocks,395 environment.newline_sequence,396 environment.keep_trailing_newline)397 lexer = _lexer_cache.get(key)398 if lexer is None:
35 unmodified lines
434435 # block suffix if trimming is enabled436 block_suffix_re = environment.trim_blocks and '\\n?' or ''437438 # strip leading spaces if lstrip_blocks is enabled439 prefix_re = {}440 if environment.lstrip_blocks:441 # use '{%+' to manually disable lstrip_blocks behavior442 no_lstrip_re = e('+')443 # detect overlap between block and variable or comment strings444 block_diff = c(r'^%s(.*)' % e(environment.block_start_string))445 # make sure we don't mistake a block for a variable or a comment446 m = block_diff.match(environment.comment_start_string)447 no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''448 m = block_diff.match(environment.variable_start_string)449 no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''450451 # detect overlap between comment and variable strings452 comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))453 m = comment_diff.match(environment.variable_start_string)454 no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''455456 lstrip_re = r'^[ \t]*'457 block_prefix_re = r'%s%s(?!%s)|%s\+?' % (458 lstrip_re,459 e(environment.block_start_string),460 no_lstrip_re,461 e(environment.block_start_string),462 )463 comment_prefix_re = r'%s%s%s|%s\+?' % (464 lstrip_re,465 e(environment.comment_start_string),466 no_variable_re,467 e(environment.comment_start_string),468 )469 prefix_re['block'] = block_prefix_re470 prefix_re['comment'] = comment_prefix_re471 else:472 block_prefix_re = '%s' % e(environment.block_start_string)473474 self.newline_sequence = environment.newline_sequence475 self.keep_trailing_newline = environment.keep_trailing_newline476477 # global lexing rules
2 unmodified lines
480 # directives481 (c('(.*?)(?:%s)' % '|'.join(482 [r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % (483 e(environment.block_start_string),447 e(environment.block_start_string),484 block_prefix_re,485 e(environment.block_end_string),486 e(environment.block_end_string)487 )] + [451 r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, r)488 r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, prefix_re.get(n,r))489 for n, r in root_tag_rules490 ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),491 # data492 (c('.+'), TOKEN_DATA, None)
25 unmodified lines
518 # raw block519 TOKEN_RAW_BEGIN: [520 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (521 e(environment.block_start_string),485 e(environment.block_start_string),522 block_prefix_re,523 e(environment.block_end_string),524 e(environment.block_end_string),525 block_suffix_re526 )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),
209 unmodified lines
modified:CHANGES+1 added
21 unmodified lines
22- Allow `contextfunction` and other decorators to be applied to `__call__`.23- Added support for changing from newline to different signs in the `wordwrap`24 filter.25- Added support for ignoring memcache errors silently.26- Added support for keeping the trailing newline in templates.2728Version 2.629-----------30(codename Convolution, released on July 24th 2011)
263 unmodified lines