added a function to parse assign targes and documented it for the extension interface
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 fb2e38a · Browse files · 5 files·+62 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+62 added−71 removed
- tests:+2 added−2 removed
- other:+60 added−69 removed
Provenance
- Commit
09c002e- Tree
3393326- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fb2e38a
5 files changed+62 added−71 removed
modified:docs/extensions.rst+3 added-3 removed
15 unmodified lines16 extension pass a list of extension classes or import paths to the17 `environment` parameter of the :class:`Environment` constructor. The following18 example creates a Jinja2 environment with the i18n extension loaded::19 20- jinja_env = Environment(extensions=['jinja.ext.i18n'])20+ jinja_env = Environment(extensions=['jinja2.ext.i18n'])21 22 23 .. _i18n-extension:24 121 unmodified lines146 expressions of different types. The following methods may be used by147 extensions:148 149 .. autoclass:: jinja2.parser.Parser150- :members: parse_expression, parse_tuple, parse_statements, skip_colon,151- skip_comma, free_identifier150+ :members: parse_expression, parse_tuple, parse_assign_target,151+ parse_statements, skip_colon, skip_comma, free_identifier152 153 .. attribute:: filename154 155 The filename of the template the parser processes. This is **not**49 unmodified linesmodified:docs/switching.rst+4 added
60 unmodified lines61 environment. In Jinja2 a similar object exists but it doesn't allow62 modifications nor is it a singleton. As inheritance is dynamic now63 multiple context objects may exist during template evaluation.64 65+Filters and Tests66+ Filters and tests are regular functions now. It's no longer necessary67+ and allowed to use factory functions.68 69+70 Templates71 ~~~~~~~~~72 73 Jinja2 has mostly the same syntax as Jinja1. The only difference is that148 unmodified linesmodified:examples/profile.py+8 added-15 removed
8 unmodified lines9 'page_title': 'mitsuhiko\'s benchmark',10 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]11 }12 13-jinja_template = JinjaEnvironment(14- line_statement_prefix='%',15- variable_start_string="${",16- variable_end_string="}"17-).from_string("""\13+source = """\14 <!doctype html>15 <html>16 <head>17 <title>${page_title|e}</title>1 unmodified line19 <body>20 <div class="header">21 <h1>${page_title|e}</h1>22 </div>27- <ul class="navigation">28- % for href, caption in [29- ('index.html', 'Index'),30- ('downloads.html', 'Downloads'),31- ('products.html', 'Products')32- ]33- <li><a href="${href|e}">${caption|e}</a></li>34- % endfor35- </ul>23 <div class="table">24 <table>25 % for row in table26 <tr>5 unmodified lines32 </table>33 </div>34 </body>35 </html>\49-""")36+"""37+jinja_template = JinjaEnvironment(38+ line_statement_prefix='%',39+ variable_start_string="${",40+ variable_end_string="}"41+).from_string(source)42+print jinja_template.environment.compile(source, raw=True)43 44 45 p = Profile()46 p.runcall(lambda: jinja_template.render(context))3 unmodified linesmodified:jinja2/parser.py+45 added-51 removed
119 unmodified lines120 121 def parse_for(self):122 """Parse a for loop."""123 lineno = self.stream.expect('name:for').lineno124- target = self.parse_tuple(simplified=True)125- if not target.can_assign():126- raise TemplateSyntaxError("can't assign to '%s'" %127- target.__class__.__name__.lower(),128- target.lineno, self.filename)129- target.set_ctx('store')124+ target = self.parse_assign_target()125 self.stream.expect('name:in')131- iter = self.parse_tuple(no_condexpr=True)126+ iter = self.parse_tuple(with_condexpr=False)127 test = None128 if self.stream.current.test('name:if'):129 self.stream.next()130 test = self.parse_expression()7 unmodified lines138 def parse_if(self):139 """Parse an if construct."""140 node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)141 while 1:147- node.test = self.parse_tuple(no_condexpr=True)142+ node.test = self.parse_tuple(with_condexpr=False)143 node.body = self.parse_statements(('name:elif', 'name:else',144 'name:endif'))145 token = self.stream.next()146 if token.test('name:elif'):37 unmodified lines184 def parse_import(self):185 node = nodes.Import(lineno=self.stream.next().lineno)186 node.template = self.parse_expression()187 self.stream.expect('name:as')193- node.target = self.stream.expect('name').value194- if not nodes.Name(node.target, 'store').can_assign():195- raise TemplateSyntaxError('can\'t assign imported template '196- 'to %r' % node.target, node.lineno,197- self.filename)188+ node.target = self.parse_assign_target(name_only=True).name189 return self.parse_import_context(node, False)190 191 def parse_from(self):192 node = nodes.FromImport(lineno=self.stream.next().lineno)14 unmodified lines207 self.stream.expect('comma')208 if self.stream.current.type is 'name':209 if parse_context():210 break220- target = nodes.Name(self.stream.current.value, 'store')221- if not target.can_assign():222- raise TemplateSyntaxError('can\'t import object named %r'223- % target.name, target.lineno,224- self.filename)225- elif target.name.startswith('__'):211+ target = self.parse_assign_target(name_only=True)212+ if target.name.startswith('__'):213 raise TemplateAssertionError('names starting with two '214 'underscores can not be '215 'imported', target.lineno,216 self.filename)230- self.stream.next()217 if self.stream.current.test('name:as'):218 self.stream.next()233- alias = self.stream.expect('name')234- if not nodes.Name(alias.value, 'store').can_assign():235- raise TemplateSyntaxError('can\'t name imported '236- 'object %r.' % alias.value,237- alias.lineno, self.filename)238- node.names.append((target.name, alias.value))219+ alias = self.parse_assign_target(name_only=True)220+ node.names.append((target.name, alias.name))221 else:222 node.names.append(target.name)223 if parse_context() or self.stream.current.type is not 'comma':224 break11 unmodified lines236 self.stream.expect('lparen')237 while self.stream.current.type is not 'rparen':238 if args:239 self.stream.expect('comma')258- token = self.stream.expect('name')259- arg = nodes.Name(token.value, 'param', lineno=token.lineno)260- if not arg.can_assign():261- raise TemplateSyntaxError("can't assign to '%s'" %262- arg.name, arg.lineno,263- self.filename)240+ arg = self.parse_assign_target(name_only=True)241 if self.stream.current.type is 'assign':242 self.stream.next()243 defaults.append(self.parse_expression())244 args.append(arg)22 unmodified lines267 return node268 269 def parse_macro(self):270 node = nodes.Macro(lineno=self.stream.next().lineno)294- node.name = self.stream.expect('name').value295- # make sure that assignments to that name are allowed296- if not nodes.Name(node.name, 'store').can_assign():297- raise TemplateSyntaxError('can\'t assign macro to %r' %298- node.target, node.lineno,299- self.filename)271+ node.name = self.parse_assign_target(name_only=True).name272 self.parse_signature(node)273 node.body = self.parse_statements(('name:endmacro',),274 drop_needle=True)275 return node6 unmodified lines282 self.stream.expect('comma')283 node.nodes.append(self.parse_expression())284 return node285 314- def parse_expression(self, no_condexpr=False):286+ def parse_assign_target(self, with_tuple=True, name_only=False):287+ """Parse an assignment target. As Jinja2 allows assignments to288+ tuples, this function can parse all allowed assignment targets. Per289+ default assignments to tuples are parsed, that can be disable however290+ by setting `with_tuple` to `False`. If only assignments to names are291+ wanted `name_only` can be set to `True`.292+ """293+ if name_only:294+ token = self.stream.expect('name')295+ target = nodes.Name(token.value, 'store', lineno=token.lineno)296+ else:297+ if with_tuple:298+ target = self.parse_tuple(simplified=True)299+ else:300+ target = self.parse_primary(with_postfix=False)301+ target.set_ctx('store')302+ if not target.can_assign():303+ raise TemplateSyntaxError('can\'t assign to %r' %304+ target.__class__.__name__.lower(),305+ target.lineno, self.filename)306+ return target307+308+ def parse_expression(self, with_condexpr=True):309 """Parse an expression. Per default all expressions are parsed, if316- the optional `no_condexpr` parameter is set to `True` conditional310+ the optional `with_condexpr` parameter is set to `False` conditional311 expressions are not parsed.312 """319- if no_condexpr:320- return self.parse_or()321- return self.parse_condexpr()313+ if with_condexpr:314+ return self.parse_condexpr()315+ return self.parse_or()316 317 def parse_condexpr(self):318 lineno = self.stream.current.lineno319 expr1 = self.parse_or()145 unmodified lines465 node = self.parse_unary()466 return nodes.Pos(node, lineno=lineno)467 return self.parse_primary()468 475- def parse_primary(self, parse_postfix=True):469+ def parse_primary(self, with_postfix=True):470 token = self.stream.current471 if token.type is 'name':472 if token.value in ('true', 'false'):473 node = nodes.Const(token.value == 'true', lineno=token.lineno)16 unmodified lines490 else:491 raise TemplateSyntaxError("unexpected token '%s'" %492 (token,), token.lineno,493 self.filename)500- if parse_postfix:494+ if with_postfix:495 node = self.parse_postfix(node)496 return node497 504- def parse_tuple(self, simplified=False, no_condexpr=False):498+ def parse_tuple(self, simplified=False, with_condexpr=True):499 """Works like `parse_expression` but if multiple expressions are500 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.501 This method could also return a regular expression instead of a tuple502 if no commas where found.3 unmodified lines506 forwarded to :meth:`parse_expression`.507 """508 lineno = self.stream.current.lineno509 if simplified:516- parse = self.parse_primary517- elif no_condexpr:518- parse = lambda: self.parse_expression(no_condexpr=True)519- else:510+ parse = lambda: self.parse_primary(with_postfix=False)511+ elif with_condexpr:512 parse = self.parse_expression513+ else:514+ parse = lambda: self.parse_expression(with_condexpr=False)515 args = []516 is_tuple = False517 while 1:518 if args:215 unmodified lines734 add_data(nodes.Const(token.value, lineno=token.lineno))735 self.stream.next()736 elif token.type is 'variable_begin':737 self.stream.next()744- add_data(self.parse_tuple())738+ add_data(self.parse_tuple(with_condexpr=True))739 self.stream.expect('variable_end')740 elif token.type is 'block_begin':741 flush_data()742 self.stream.next()20 unmodified linesmodified:tests/test_security.py+2 added-2 removed
60 unmodified lines61 >>> env = MODULE.SandboxedEnvironment()62 >>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")63 Traceback (most recent call last):64 ...65-TemplateSyntaxError: can't assign to 'subscript' (line 1)65+TemplateSyntaxError: expected token 'in', got '.' (line 1)66 >>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")67 Traceback (most recent call last):68 ...69-TemplateSyntaxError: can't assign to 'tuple' (line 1)69+TemplateSyntaxError: expected token 'in', got '.' (line 1)70 '''