Skip to content
Myr

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

8 files+98 added−27 removed

modified:docs/templates.rst+8 added
250 unmodified lines
251 <li><a href="{{ href }}">{{ caption }}</a></li>252 # endfor253 </ul>254255Since Jinja 2.2 line-based comments are available as well. For example if256the line-comment prefix is configured to be ``##`` everything from ``##`` to257the end of the line is ignored (excluding the newline sign)::258259 # for item in seq:260 <li>{{ item }}</li> ## this comment is ignored261 # endfor262263264.. _template-inheritance:265266Template Inheritance267--------------------
979 unmodified lines
modified:jinja2/defaults.py+1 added
17 unmodified lines
18VARIABLE_END_STRING = '}}'19COMMENT_START_STRING = '{#'20COMMENT_END_STRING = '#}'21LINE_STATEMENT_PREFIX = None22LINE_COMMENT_PREFIX = None23TRIM_BLOCKS = False24NEWLINE_SEQUENCE = '\n'2526
14 unmodified lines
modified:jinja2/environment.py+16 added-7 removed
116 unmodified lines
117 `line_statement_prefix`118 If given and a string, this will be used as prefix for line based119 statements. See also :ref:`line-statements`.120121 `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`.124125 .. versionadded:: 2.2126127 `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 lines
203 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 lines
234 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_sequence241242 # runtime information
30 unmodified lines
273274 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 overlayed
282 unmodified lines
567 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 lines
578 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)586587 @classmethod588 def from_code(cls, environment, code, globals, uptodate=None):
261 unmodified lines
modified:jinja2/ext.py+1 added
427 unmodified lines
428 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 shared
21 unmodified lines
modified:jinja2/lexer.py+38 added-19 removed
76 unmodified lines
77TOKEN_COMMENT_END = intern('comment_end')78TOKEN_COMMENT = intern('comment')79TOKEN_LINESTATEMENT_BEGIN = intern('linestatement_begin')80TOKEN_LINESTATEMENT_END = intern('linestatement_end')81TOKEN_LINECOMMENT_BEGIN = intern('linecomment_begin')82TOKEN_LINECOMMENT_END = intern('linecomment_end')83TOKEN_LINECOMMENT = intern('linecomment')84TOKEN_DATA = intern('data')85TOKEN_INITIAL = intern('initial')86TOKEN_EOF = intern('eof')87
31 unmodified lines
119assert len(operators) == len(reverse_operators), 'operators dropped'120operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in121 sorted(operators, key=lambda x: -len(x))))122123ignored_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])127128129def 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))134135136def 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 ]147148 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)))154155 return [x[1:] for x in sorted(rules, reverse=True)]156157158class Failure(object):159 """Class that raises a `TemplateSyntaxError` if called.160 Used by the `Lexer` to specify known errors.161 """
169 unmodified lines
331 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 lines
370 # 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)375350 # 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]353354 # 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))359376 # block suffix if trimming is enabled377 block_suffix_re = environment.trim_blocks and '\\n?' or ''378379 self.newline_sequence = environment.newline_sequence
51 unmodified lines
431 ],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 }441442 def _normalize_newlines(self, value):443 """Called for strings and template data to normlize it to unicode."""
9 unmodified lines
453 """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 lines
modified:tests/test_old_bugs.py+6 added
58 unmodified lines
59def test_weird_inline_comment():60 env = Environment(line_statement_prefix='%')61 raises(TemplateSyntaxError, env.from_string,62 '% for item in seq {# missing #}\n...% endfor')636465def 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 lines
27 ${item}28<!--- endfor -->'''2930MAKO_SYNTAX = '''\31<%# regular comment %>32% for item in seq:33 ${item}34% endfor'''3536MAKO_SYNTAX_LINECOMMENTS = '''\37<%# regular comment %>38% for item in seq:39 ${item} ## the rest of the stuff40% endfor'''4142BALANCING = '''{{{'foo':'bar'}.foo}}'''4344STARTCOMMENT = '''{# foo comment45and bar comment #}46{% macro blub() %}foo{% endmacro %}47{{ blub() }}'''4849LINE_SYNTAX_PRIORITY = '''\50/* ignore me.51 I'm a multiline comment */52# for item in seq:53* ${item} ## this is just extra stuff54# endfor55'''565758def test_php_syntax():59 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')60 tmpl = env.from_string(PHP_SYNTAX)61 assert tmpl.render(seq=range(5)) == '01234'
24 unmodified lines
86def 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)9192 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)969798def 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 lines
18- 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.2324Version 2.1.125-------------26(Bugfix release)
84 unmodified lines