Added support for line-based comments.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 1dcafe5 · Browse files · 8 files·+98 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+98 added−27 removed
- tests:+33 added−1 removed
- other:+65 added−26 removed
Provenance
- Commit
59b6bd5- Tree
7c5a171- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1dcafe5
8 files changed+98 added−27 removed
modified:docs/templates.rst+8 added
250 unmodified lines251 <li><a href="{{ href }}">{{ caption }}</a></li>252 # endfor253 </ul>254 255+Since Jinja 2.2 line-based comments are available as well. For example if256+the line-comment prefix is configured to be ``##`` everything from ``##`` to257+the end of the line is ignored (excluding the newline sign)::258 259+ # for item in seq:260+ <li>{{ item }}</li> ## this comment is ignored261+ # endfor262+263+264 .. _template-inheritance:265 266 Template Inheritance267 --------------------979 unmodified linesmodified:jinja2/defaults.py+1 added
17 unmodified lines18 VARIABLE_END_STRING = '}}'19 COMMENT_START_STRING = '{#'20 COMMENT_END_STRING = '#}'21 LINE_STATEMENT_PREFIX = None22+LINE_COMMENT_PREFIX = None23 TRIM_BLOCKS = False24 NEWLINE_SEQUENCE = '\n'25 26 14 unmodified linesmodified:jinja2/environment.py+16 added-7 removed
116 unmodified lines117 `line_statement_prefix`118 If given and a string, this will be used as prefix for line based119 statements. See also :ref:`line-statements`.120 121+ `line_comment_prefix`122+ If given and a string, this will be used as prefix for line based123+ based comments. See also :ref:`line-statements`.124+125+ .. versionadded:: 2.2126+127 `trim_blocks`128 If this is set to ``True`` the first newline after a block is129 removed (block, not variable tag!). Defaults to `False`.130 72 unmodified lines203 variable_end_string=VARIABLE_END_STRING,204 comment_start_string=COMMENT_START_STRING,205 comment_end_string=COMMENT_END_STRING,206 line_statement_prefix=LINE_STATEMENT_PREFIX,207+ line_comment_prefix=LINE_COMMENT_PREFIX,208 trim_blocks=TRIM_BLOCKS,209 newline_sequence=NEWLINE_SEQUENCE,210 extensions=(),211 optimized=True,22 unmodified lines234 self.variable_end_string = variable_end_string235 self.comment_start_string = comment_start_string236 self.comment_end_string = comment_end_string237 self.line_statement_prefix = line_statement_prefix238+ self.line_comment_prefix = line_comment_prefix239 self.trim_blocks = trim_blocks240 self.newline_sequence = newline_sequence241 242 # runtime information30 unmodified lines273 274 def overlay(self, block_start_string=missing, block_end_string=missing,275 variable_start_string=missing, variable_end_string=missing,276 comment_start_string=missing, comment_end_string=missing,269- line_statement_prefix=missing, trim_blocks=missing,270- extensions=missing, optimized=missing, undefined=missing,271- finalize=missing, autoescape=missing, loader=missing,272- cache_size=missing, auto_reload=missing,277+ line_statement_prefix=missing, line_comment_prefix=missing,278+ trim_blocks=missing, extensions=missing, optimized=missing,279+ undefined=missing, finalize=missing, autoescape=missing,280+ loader=missing, cache_size=missing, auto_reload=missing,281 bytecode_cache=missing):282 """Create a new overlay environment that shares all the data with the283 current environment except of cache and the overriden attributes.284 Extensions cannot be removed for a overlayed environment. A overlayed282 unmodified lines567 variable_end_string=VARIABLE_END_STRING,568 comment_start_string=COMMENT_START_STRING,569 comment_end_string=COMMENT_END_STRING,570 line_statement_prefix=LINE_STATEMENT_PREFIX,571+ line_comment_prefix=LINE_COMMENT_PREFIX,572 trim_blocks=TRIM_BLOCKS,573 newline_sequence=NEWLINE_SEQUENCE,574 extensions=(),575 optimized=True,2 unmodified lines578 autoescape=False):579 env = get_spontaneous_environment(580 block_start_string, block_end_string, variable_start_string,581 variable_end_string, comment_start_string, comment_end_string,573- line_statement_prefix, trim_blocks, newline_sequence,574- frozenset(extensions), optimized, undefined, finalize,575- autoescape, None, 0, False, None)582+ line_statement_prefix, line_comment_prefix, trim_blocks,583+ newline_sequence, frozenset(extensions), optimized, undefined,584+ finalize, autoescape, None, 0, False, None)585 return env.from_string(source, template_class=cls)586 587 @classmethod588 def from_code(cls, environment, code, globals, uptodate=None):261 unmodified linesmodified:jinja2/ext.py+1 added
427 unmodified lines428 options.get('variable_end_string', VARIABLE_END_STRING),429 options.get('comment_start_string', COMMENT_START_STRING),430 options.get('comment_end_string', COMMENT_END_STRING),431 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,432+ options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,433 str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \434 ('1', 'on', 'yes', 'true'),435 NEWLINE_SEQUENCE, frozenset(extensions),436 # fill with defaults so that environments are shared21 unmodified linesmodified:jinja2/lexer.py+38 added-19 removed
76 unmodified lines77 TOKEN_COMMENT_END = intern('comment_end')78 TOKEN_COMMENT = intern('comment')79 TOKEN_LINESTATEMENT_BEGIN = intern('linestatement_begin')80 TOKEN_LINESTATEMENT_END = intern('linestatement_end')81+TOKEN_LINECOMMENT_BEGIN = intern('linecomment_begin')82+TOKEN_LINECOMMENT_END = intern('linecomment_end')83+TOKEN_LINECOMMENT = intern('linecomment')84 TOKEN_DATA = intern('data')85 TOKEN_INITIAL = intern('initial')86 TOKEN_EOF = intern('eof')87 31 unmodified lines119 assert len(operators) == len(reverse_operators), 'operators dropped'120 operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in121 sorted(operators, key=lambda x: -len(x))))122 123+ignored_tokens = frozenset([TOKEN_COMMENT_BEGIN, TOKEN_COMMENT,124+ TOKEN_COMMENT_END, TOKEN_WHITESPACE,125+ TOKEN_WHITESPACE, TOKEN_LINECOMMENT_BEGIN,126+ TOKEN_LINECOMMENT_END, TOKEN_LINECOMMENT])127 128+129 def count_newlines(value):130 """Count the number of newline characters in the string. This is131 useful for extensions that filter a stream.132 """133 return len(newline_re.findall(value))134 135 136+def compile_rules(environment):137+ """Compiles all the rules from the environment into a list of rules."""138+ e = re.escape139+ rules = [140+ (len(environment.comment_start_string), 'comment',141+ e(environment.comment_start_string)),142+ (len(environment.block_start_string), 'block',143+ e(environment.block_start_string)),144+ (len(environment.variable_start_string), 'variable',145+ e(environment.variable_start_string)),146+ ]147+148+ if environment.line_statement_prefix is not None:149+ rules.append((len(environment.line_statement_prefix), 'linestatement',150+ '^\\s*' + e(environment.line_statement_prefix)))151+ if environment.line_comment_prefix is not None:152+ rules.append((len(environment.line_comment_prefix), 'linecomment',153+ '\\s*' + e(environment.line_comment_prefix)))154+155+ return [x[1:] for x in sorted(rules, reverse=True)]156+157+158 class Failure(object):159 """Class that raises a `TemplateSyntaxError` if called.160 Used by the `Lexer` to specify known errors.161 """169 unmodified lines331 environment.variable_end_string,332 environment.comment_start_string,333 environment.comment_end_string,334 environment.line_statement_prefix,335+ environment.line_comment_prefix,336 environment.trim_blocks,337 environment.newline_sequence)338 lexer = _lexer_cache.get(key)339 if lexer is None:30 unmodified lines370 # as expected when we have parsing rules like <% for block and371 # <%= for variables. (if someone wants asp like syntax)372 # variables are just part of the rules if variable processing373 # is required.343- root_tag_rules = [344- ('comment', environment.comment_start_string),345- ('block', environment.block_start_string),346- ('variable', environment.variable_start_string)347- ]348- root_tag_rules.sort(key=lambda x: -len(x[1]))374+ root_tag_rules = compile_rules(environment)375 350- # now escape the rules. This is done here so that the escape351- # signs don't count for the lengths of the tags.352- root_tag_rules = [(a, e(b)) for a, b in root_tag_rules]353-354- # if we have a line statement prefix we need an extra rule for355- # that. We add this rule *after* all the others.356- if environment.line_statement_prefix is not None:357- prefix = e(environment.line_statement_prefix)358- root_tag_rules.insert(0, ('linestatement', '^\s*' + prefix))359-376 # block suffix if trimming is enabled377 block_suffix_re = environment.trim_blocks and '\\n?' or ''378 379 self.newline_sequence = environment.newline_sequence51 unmodified lines431 ],432 # line statements433 TOKEN_LINESTATEMENT_BEGIN: [434 (c(r'\s*(\n|$)'), TOKEN_LINESTATEMENT_END, '#pop')419- ] + tag_rules435+ ] + tag_rules,436+ # line comments437+ TOKEN_LINECOMMENT_BEGIN: [438+ (c(r'.*?(?=\n|$)'), TOKEN_LINECOMMENT_END, '#pop')439+ ]440 }441 442 def _normalize_newlines(self, value):443 """Called for strings and template data to normlize it to unicode."""9 unmodified lines453 """This is called with the stream as returned by `tokenize` and wraps454 every token in a :class:`Token` and converts the value.455 """456 for lineno, token, value in stream:437- if token in ('comment_begin', 'comment', 'comment_end',438- 'whitespace'):457+ if token in ignored_tokens:458 continue459 elif token == 'linestatement_begin':460 token = 'block_begin'461 elif token == 'linestatement_end':167 unmodified linesmodified:tests/test_old_bugs.py+6 added
58 unmodified lines59 def test_weird_inline_comment():60 env = Environment(line_statement_prefix='%')61 raises(TemplateSyntaxError, env.from_string,62 '% for item in seq {# missing #}\n...% endfor')63+64+65+def test_old_macro_loop_scoping_bug(env):66+ tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'67+ '{% macro i() %}3{% endmacro %}{{ i() }}')68+ assert tmpl.render() == '123'modified:tests/test_parser.py+27 added-1 removed
26 unmodified lines27 ${item}28 <!--- endfor -->'''29 30 MAKO_SYNTAX = '''\31+<%# regular comment %>32 % for item in seq:33 ${item}34 % endfor'''35 36+MAKO_SYNTAX_LINECOMMENTS = '''\37+<%# regular comment %>38+% for item in seq:39+ ${item} ## the rest of the stuff40+% endfor'''41+42 BALANCING = '''{{{'foo':'bar'}.foo}}'''43 44 STARTCOMMENT = '''{# foo comment45 and bar comment #}46 {% macro blub() %}foo{% endmacro %}47 {{ blub() }}'''48 49+LINE_SYNTAX_PRIORITY = '''\50+/* ignore me.51+ I'm a multiline comment */52+# for item in seq:53+* ${item} ## this is just extra stuff54+# endfor55+'''56 57+58 def test_php_syntax():59 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')60 tmpl = env.from_string(PHP_SYNTAX)61 assert tmpl.render(seq=range(5)) == '01234'24 unmodified lines86 def test_line_syntax():87 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')88 tmpl = env.from_string(MAKO_SYNTAX)89 assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \75- range(5)90+ range(5)91+92+ env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')93+ tmpl = env.from_string(MAKO_SYNTAX_LINECOMMENTS)94+ assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \95+ range(5)96+97+98+def test_line_syntax_priority():99+ env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')100+ tmpl = env.from_string(LINE_SYNTAX_PRIORITY)101+ assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'modified:CHANGES+1 added
17 unmodified lines18 - Fixed a bug that caused internal errors if names where used as iteration19 variable and regular variable *after* the loop if that variable was unused20 *before* the loop. (#331)21 - Added support for optional `scoped` modifier to blocks.22+- Added support for line-comments.23 24 Version 2.1.125 -------------26 (Bugfix release)84 unmodified lines