Skip to content
Myr

[svn] jinja can now handle variables and blocks with the same delimiters. Thanks Getty for the "nice" discussion today -.-

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 4965987 · Browse files · 4 files+132 added−40 removed
This commit

State

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

Diff stats

4 files+132 added−40 removed

  • other:+132 added−40 removed

4 files+132 added−40 removed

modified:docs/src/altsyntax.txt+24 added
77 unmodified lines
78in the expression. That means that you can use small delimiters like single79braces or parenthesis. So if you want to have your variables to look like80``${expr}`` and you still want to use dicts in such expressions you need81Jinja 1.1 or higher.828384Block / Variable Tag Unification85--------------------------------8687If variable end and start tags are `None` or look the same as block tags and88you're running Jinja 1.1 or later the parser will switch into the89`no_comment_block` mode. In that mode it will try to match something as block90first and continue treating it as variable block if there is no known91directive for that name. Example:9293.. sourcecode:: python9495 env = Environment('{', '}', None, None, '{*', '*}')9697This now allows smarty like templates:9899.. sourcecode:: smarty100101 {if something == 42}102 Something is the answer to all questions and stuff like that.103 {else}104 Something is {something}.105 {endif}
modified:jinja/lexer.py+28 added-9 removed
129 unmodified lines
130 (operator_re, 'operator', None),131 (string_re, 'string', None)132 ]133134 #: if variables and blocks have the same delimiters we won't135 #: receive any variable blocks in the parser. This variable is `True`136 #: if we need that.137 self.no_variable_block = (138 (environment.variable_start_string is139 environment.variable_end_string is None) or140 (environment.variable_start_string ==141 environment.block_start_string and142 environment.variable_end_string ==143 environment.block_end_string)144 )145146 # assamble the root lexing rule. because "|" is ungreedy147 # we have to sort by length so that the lexer continues working148 # as expected when we have parsing rules like <% for block and149 # <%= for variables. (if someone wants asp like syntax)150 # variables are just part of the rules if variable processing151 # is required.152 root_tag_rules = [153 ('comment', environment.comment_start_string),140 ('block', environment.block_start_string),141 ('variable', environment.variable_start_string)154 ('block', environment.block_start_string)155 ]156 if not self.no_variable_block:157 root_tag_rules.append(('variable',158 environment.variable_start_string))159 root_tag_rules.sort(lambda a, b: cmp(len(b[1]), len(a[1])))160161 # block suffix if trimming is enabled162 block_suffix_re = environment.trim_blocks and '\\n?' or ''
33 unmodified lines
196 e(environment.block_end_string),197 block_suffix_re198 )), 'block_end', '#pop'),199 ] + tag_rules,184 # variables185 'variable_begin': [186 (c('\-%s\s*|%s' % (187 e(environment.variable_end_string),188 e(environment.variable_end_string)189 )), 'variable_end', '#pop')190 ] + tag_rules,200 # raw block201 'raw': [202 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (203 e(environment.block_start_string),
5 unmodified lines
209 (c('(.)'), (Failure('Missing end of raw directive'),), None)210 ]211 }212213 # only add the variable rules to the list if we process variables214 # the variable_end_string variable could be None and break things.215 if not self.no_variable_block:216 self.rules['variable_begin'] = [217 (c('\-%s\s*|%s' % (218 e(environment.variable_end_string),219 e(environment.variable_end_string)220 )), 'variable_end', '#pop')221 ] + tag_rules222223 def tokenize(self, source, filename=None):224 """225 Simple tokenize function that yields ``(position, type, contents)``226 tuples. Wrap the generator returned by this function in a
146 unmodified lines
modified:jinja/parser.py+76 added-31 removed
90 unmodified lines
91 'elif', 'else', 'endblock', 'endfilter', 'endfor', 'endif',92 'endmacro', 'endraw', 'endtrans', 'pluralize'93 ])9495 #: get the `no_variable_block` flag96 self.no_variable_block = self.environment.lexer.no_variable_block9798 self.tokenstream = environment.lexer.tokenize(source, filename)99100 def handle_raw_directive(self, lineno, gen):101 """
247 unmodified lines
349 def handle_trans_directive(self, lineno, gen):350 """351 Handle translatable sections.352 """353 def process_variable(lineno, token, name):354 if token != 'name':355 raise TemplateSyntaxError('can only use variable not '356 'constants or expressions '357 'in translation variable '358 'blocks.', lineno,359 self.filename)360 # plural name without trailing "_"? that's a keyword361 if not name.endswith('_'):362 raise TemplateSyntaxError('illegal use of keyword '363 "'%s' as identifier in "364 'trans block.' %365 name, lineno, self.filename)366 name = name[:-1]367 if name not in replacements:368 raise TemplateSyntaxError('unregistered translation '369 "variable '%s'." %370 name, lineno,371 self.filename)372 # check that we don't have an expression here, thus the373 # next token *must* be a variable_end token (or a374 # block_end token when in no_variable_block mode)375 next_token = self.tokenstream.next()[1]376 if next_token != 'variable_end' and not \377 (self.no_variable_block and next_token == 'block_end'):378 raise TemplateSyntaxError('you cannot use variable '379 'expressions inside trans '380 'tags. apply filters '381 'in the trans header.',382 lineno, self.filename)383 buf.append('%%(%s)s' % name)384385 # save the initial line number for the resulting node386 flineno = lineno387 try:388 # check for string translations
56 unmodified lines
445 if token == 'comment_begin':446 self.tokenstream.drop_until(end_of_comment, True)447 # nested variables448 elif token == 'variable_begin':414 _, variable_token, variable_name = self.tokenstream.next()415 if variable_token != 'name':416 raise TemplateSyntaxError('can only use variable not '417 'constants or expressions '418 'in translation variable '419 'blocks.', lineno,420 self.filename)421 # plural name without trailing "_"? that's a keyword422 if not variable_name.endswith('_'):423 raise TemplateSyntaxError('illegal use of keyword '424 "'%s' as identifier in "425 'trans block.' %426 variable_name,427 lineno, self.filename)428 variable_name = variable_name[:-1]429 if variable_name not in replacements:430 raise TemplateSyntaxError('unregistered translation '431 "variable '%s'." %432 variable_name, lineno,433 self.filename)434 if self.tokenstream.next()[1] != 'variable_end':435 raise TemplateSyntaxError('you cannot use variable '436 'expressions inside trans '437 'tags. apply filters '438 'in the trans header.',439 lineno, self.filename)440 buf.append('%%(%s)s' % variable_name)449 process_variable(*self.tokenstream.next())450 # nested blocks are not supported, just look for end blocks451 elif token == 'block_begin':452 _, block_token, block_name = self.tokenstream.next()453 if block_token != 'name' or \
15 unmodified lines
469 # endtrans. Raise the "unknown directive"470 # exception rather than the "not allowed"471 if block_name not in self.directives:472 if block_name.endswith('_'):473 # if we don't have a variable block we474 # have to process this as variable.475 if self.no_variable_block:476 process_variable(_, block_token,477 block_name)478 continue479 block_name = block_name[:-1]480 raise TemplateSyntaxError('unknown directive'481 "'%s'" % block_name,482 lineno,483 self.filename)484 # we have something different and are in the485 # special no_variable_block mode. process this486 # as variable487 elif self.no_variable_block:488 process_variable(_, block_token, block_name)489 continue490 # if it's indeed a known directive we better491 # raise an exception informing the user about492 # the fact that we don't support blocks in493 # translatable sections.
206 unmodified lines
700 insertions))701 # clear the buffer702 del data_buffer[:]703704 def process_variable(gen):705 data_buffer.append(('variable', lineno, tuple(gen)))706707 lineno = self.tokenstream.last[0]708 result = nodes.NodeList(lineno)709 data_buffer = []710 for lineno, token, data in self.tokenstream:
4 unmodified lines
715 # this token marks the begin or a variable section.716 # parse everything till the end of it.717 elif token == 'variable_begin':718 gen = self.tokenstream.fetch_until(end_of_variable, True)695 data_buffer.append(('variable', lineno, tuple(gen)))719 process_variable(gen)720721 # this token marks the start of a block. like for variables722 # just parse everything until the end of the block723 elif token == 'block_begin':
1 unmodified line
725 # data back726 if data_buffer:727 flush_data_buffer()728729 node = None730 gen = self.tokenstream.fetch_until(end_of_block, True)731 try:732 lineno, token, data = gen.next()733 except StopIteration:
1 unmodified line
735 lineno, self.filename)736737 # first token *must* be a name token738 if token != 'name':739 # well, not always. if we have a lexer without variable740 # blocks configured we process these tokens as variable741 # block.742 if self.no_variable_block:743 process_variable([(lineno, token, data)] + list(gen))744 else:714 raise TemplateSyntaxError('unexpected %r token (%r)' % (715 token, data), lineno,716 self.filename)745 raise TemplateSyntaxError('unexpected %r token (%r)' %746 (token, data), lineno,747 self.filename)748749 # if a test function is passed to subparse we check if we750 # reached the end of such a requested block.751 if test is not None and test(lineno, token, data):
12 unmodified lines
764 str(data), lineno,765 self.filename)766 # keyword or unknown name with trailing slash767 else:768 # non name token in no_variable_block mode.769 if token != 'name' and self.no_variable_block:770 process_variable([(lineno, token, data)] +771 list(gen))772 continue773 if data.endswith('_'):774 # it was a non keyword identifier and we have775 # no variable tag. sounds like we should process776 # this as variable tag777 if self.no_variable_block:778 process_variable([(lineno, token, data)] +779 list(gen))780 continue781 # otherwise strip the trailing underscore for the782 # exception that is raised783 data = data[:-1]784 raise TemplateSyntaxError('unknown directive %r' %785 str(data), lineno,786 self.filename)
46 unmodified lines
modified:CHANGES+4 added
16 unmodified lines
17 bracket balance in order to not break variable tags apart if they18 are configured to look like this: ``${expr}``. This also fixes19 the problem with nested dicts in variable expressions.2021- it's now possible to configure the variable blocks to look the22 same as the block delimiters. Thus you can set the syntax to something23 like ``{ / }`` for both blocks and variables.2425- added whitespace management system for the template designer.2627- some small bugfixes.28
78 unmodified lines