Skip to content
Myr

added parsing code for "for item in seq recursive" and improved parser interface a bit

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 27069d7 · Browse files · 10 files+143 added−60 removed
This commit

State

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

Diff stats

10 files+143 added−60 removed

  • other:+143 added−60 removed

10 files+143 added−60 removed

modified:docs/cache_extension.py+1 added-1 removed
25 unmodified lines
26 args = [parser.parse_expression()]2728 # if there is a comma, the user provided a timeout. If not use29 # None as second parameter.30 if parser.skip_comma():30 if parser.stream.skip_if('comma'):31 args.append(parser.parse_expression())32 else:33 args.append(nodes.Const(None))34
22 unmodified lines
modified:docs/extensions.rst+2 added-2 removed
153 unmodified lines
154extensions:155156.. autoclass:: jinja2.parser.Parser157 :members: parse_expression, parse_tuple, parse_assign_target,158 parse_statements, skip_colon, skip_comma, free_identifier158 parse_statements, free_identifier159160 .. attribute:: filename161162 The filename of the template the parser processes. This is **not**
5 unmodified lines
168169 The current :class:`~jinja2.lexer.TokenStream`170171.. autoclass:: jinja2.lexer.TokenStream172 :members: push, look, eos, skip, next, expect172 :members: push, look, eos, skip, next, next_if, skip_if, expect173174 .. attribute:: current175176 The current :class:`~jinja2.lexer.Token`.
35 unmodified lines
modified:docs/index.rst+1 added
13 unmodified lines
14 templates15 extensions16 integration17 switching18 tricks1920 changelog2122If you can't find the information you're looking for, have a look at the
4 unmodified lines
modified:docs/templates.rst+2 added-1 removed
279 unmodified lines
280The ``{% extends %}`` tag is the key here. It tells the template engine that281this template "extends" another template. When the template system evaluates282this template, first it locates the parent. The extends tag should be the283first tag in the template. Everything before it is printed out normally and284may cause confusion.284may cause confusion. For details about this behavior and how to take285advantage of it, see :ref:`null-master-fallback`.286287The filename of the template depends on the template loader. For example the288:class:`FileSystemLoader` allows you to access other templates by giving the289filename. You can access templates in subdirectories with an slash::
716 unmodified lines
added:docs/tricks.rst+81 added
1Tipps and Tricks2================34.. highlight:: html+jinja56This part of the documentation shows some tipps and tricks for Jinja27templates.8910.. _null-master-fallback:1112Null-Master Fallback13--------------------1415Jinja2 supports dynamic inheritance and does not distinguish between parent16and child template as long as no `extends` tag is visited. While this leads17to the surprising behavior that everything before the first `extends` tag18including whitespace is printed out instead of being igored, it can be used19for a neat trick.2021Usually child templates extend from one template that adds a basic HTML22skeleton. However it's possible put the `extends` tag into an `if` tag to23only extend from the layout template if the `standalone` variable evaluates24to false which it does per default if it's not defined. Additionally a very25basic skeleton is added to the file so that if it's indeed rendered with26`standalone` set to `True` a very basic HTML skeleton is added::2728 {% if not standalone %}{% extends 'master.html' %}{% endif -%}29 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">30 <title>{% block title %}The Page Title{% endblock %}</title>31 <link rel="stylesheet" href="style.css" type="text/css">32 {% block body %}33 <p>This is the page body.</p>34 {% endblock %}353637Alternating Rows38----------------3940If you want to have different styles for each row of a table or41list you can use the `cycle` method on the `loop` object::4243 <ul>44 {% for row in rows %}45 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>46 {% endfor %}47 </ul>4849`cycle` can take an unlimited amount of strings. Each time this50tag is encountered the next item from the list is rendered.515253Highlighting Active Menu Items54------------------------------5556Often you want to have a navigation bar with an active navigation57item. This is really simple to achieve. Because assignments outside58of `block`\s in child templates are global and executed before the layout59template is evaluated it's possible to define the active menu item in the60child template::6162 {% extends "layout.html" %}63 {% set active_page = "index" %}6465The layout template can then access `active_page`. Additionally it makes66sense to defined a default for that variable::6768 {% navigation_bar = [69 ('/', 'index', 'Index'),70 ('/downloads/', 'downloads', 'Downloads'),71 ('/about/', 'about', 'About')72 ] -%}73 {% active_page = active_page|default('index') -%}74 ...75 <ul id="navigation">76 {% for href, id, caption in navigation_bar %}77 <li{% if id == active_page %} class="active"{% endif78 %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>79 {% endfor %}80 </ul>81 ...
modified:jinja2/compiler.py+2 added-2 removed
1173 unmodified lines
1174 visit_Not = uaop('not ')1175 del binop, uaop11761177 def visit_Concat(self, node, frame):1178 self.write('%s((' % self.environment.autoescape and1179 'markup_join' or 'unicode_join')1178 self.write('%s((' % (self.environment.autoescape and1179 'markup_join' or 'unicode_join'))1180 for arg in node.nodes:1181 self.visit(arg, frame)1182 self.write(', ')1183 self.write('))')
98 unmodified lines
modified:jinja2/ext.py+1 added-1 removed
143 unmodified lines
144 if variables:145 parser.stream.expect('comma')146147 # skip colon for python compatibility148 if parser.skip_colon():148 if parser.stream.skip_if('colon'):149 break150151 name = parser.stream.expect('name')152 if name.value in variables:
211 unmodified lines
modified:jinja2/lexer.py+19 added-11 removed
217 unmodified lines
218 """Got n tokens ahead."""219 for x in xrange(n):220 self.next()221222 def next(self, skip_eol=True):222 def next_if(self, expr):223 """Perform the token test and return the token if it matched.224 Otherwise the return value is `None`.225 """226 if self.current.test(expr):227 return self.next()228229 def skip_if(self, expr):230 """Like `next_if` but only returns `True` or `False`."""231 return self.next_if(expr) is not None232233 def next(self):234 """Go one token ahead and return the old one"""235 rv = self.current225 while 1:226 if self._pushed:227 self.current = self._pushed.popleft()228 elif self.current.type is not 'eof':229 try:230 self.current = self._next()231 except StopIteration:232 self.close()236 if self._pushed:237 self.current = self._pushed.popleft()238 elif self.current.type is not 'eof':239 try:240 self.current = self._next()241 except StopIteration:242 self.close()233 if not skip_eol or self.current.type is not 'eol':234 break243 return rv244245 def close(self):246 """Close the stream."""
333 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
271 unmodified lines
272 `else` block. If no else node exists it has to be an empty list.273274 For filtered nodes an expression can be stored as `test`, otherwise `None`.275 """276 fields = ('target', 'iter', 'body', 'else_', 'test')276 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')277278279class If(Stmt):280 """If `test` is true, `body` is rendered, else `else_`."""
489 unmodified lines
modified:jinja2/parser.py+33 added-41 removed
34 unmodified lines
35 for tag in extension.tags:36 self.extensions[tag] = extension.parse37 self._last_identifier = 03839 def is_tuple_end(self):39 def is_tuple_end(self, extra_end_rules=None):40 """Are we at the end of a tuple?"""41 return self.stream.current.type in ('variable_end', 'block_end',42 'rparen') or \43 self.stream.current.test('name:in')4445 def skip_colon(self):46 """If there is a colon, skip it and return `True`, else `False`."""47 if self.stream.current.type is 'colon':48 self.stream.next()41 if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):42 return True43 elif extra_end_rules is not None:44 return self.stream.current.test_any(extra_end_rules)45 return False4652 def skip_comma(self):53 """If there is a comma, skip it and return `True`, else `False`."""54 if self.stream.current.type is 'comma':55 self.stream.next()56 return True57 return False5847 def free_identifier(self, lineno=None):48 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""49 self._last_identifier += 150 rv = object.__new__(nodes.InternalName)
43 unmodified lines
94 the call is the matched end token. If this is not wanted `drop_needle`95 can be set to `True` and the end token is removed.96 """97 # the first token may be a colon for python compatibility110 self.skip_colon()98 self.stream.skip_if('colon')99100 # in the future it would be possible to add whole code sections101 # by adding some sort of end of statement token and parsing those here.102 self.stream.expect('block_end')
5 unmodified lines
108109 def parse_for(self):110 """Parse a for loop."""111 lineno = self.stream.expect('name:for').lineno124 target = self.parse_assign_target()112 target = self.parse_assign_target(extra_end_rules=('name:in',))113 self.stream.expect('name:in')126 iter = self.parse_tuple(with_condexpr=False)114 iter = self.parse_tuple(with_condexpr=False,115 extra_end_rules=('name:recursive',))116 test = None128 if self.stream.current.test('name:if'):129 self.stream.next()117 if self.stream.skip_if('name:if'):118 test = self.parse_expression()119 recursive = self.stream.skip_if('name:recursive')120 body = self.parse_statements(('name:endfor', 'name:else'))121 if self.stream.next().value == 'endfor':122 else_ = []123 else:124 else_ = self.parse_statements(('name:endfor',), drop_needle=True)136 return nodes.For(target, iter, body, else_, test, lineno=lineno)125 return nodes.For(target, iter, body, else_, test,126 recursive, lineno=lineno)127128 def parse_if(self):129 """Parse an if construct."""130 node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
72 unmodified lines
203 raise TemplateAssertionError('names starting with two '204 'underscores can not be '205 'imported', target.lineno,206 self.filename)217 if self.stream.current.test('name:as'):218 self.stream.next()207 if self.stream.skip_if('name:as'):208 alias = self.parse_assign_target(name_only=True)209 node.names.append((target.name, alias.name))210 else:211 node.names.append(target.name)
2 unmodified lines
214 else:215 break216 if not hasattr(node, 'with_context'):217 node.with_context = False229 if self.stream.current.type is 'comma':230 self.stream.next()218 self.stream.skip_if('comma')219 return node220221 def parse_signature(self, node):222 node.args = args = []
2 unmodified lines
225 while self.stream.current.type is not 'rparen':226 if args:227 self.stream.expect('comma')228 arg = self.parse_assign_target(name_only=True)241 if self.stream.current.type is 'assign':242 self.stream.next()229 if self.stream.skip_if('assign'):230 defaults.append(self.parse_expression())231 args.append(arg)232 self.stream.expect('rparen')233
35 unmodified lines
269 self.stream.expect('comma')270 node.nodes.append(self.parse_expression())271 return node272286 def parse_assign_target(self, with_tuple=True, name_only=False):273 def parse_assign_target(self, with_tuple=True, name_only=False,274 extra_end_rules=None):275 """Parse an assignment target. As Jinja2 allows assignments to276 tuples, this function can parse all allowed assignment targets. Per277 default assignments to tuples are parsed, that can be disable however278 by setting `with_tuple` to `False`. If only assignments to names are291 wanted `name_only` can be set to `True`.279 wanted `name_only` can be set to `True`. The `extra_end_rules`280 parameter is forwarded to the tuple parsing function.281 """282 if name_only:283 token = self.stream.expect('name')284 target = nodes.Name(token.value, 'store', lineno=token.lineno)285 else:286 if with_tuple:298 target = self.parse_tuple(simplified=True)287 target = self.parse_tuple(simplified=True,288 extra_end_rules=extra_end_rules)289 else:290 target = self.parse_primary(with_postfix=False)291 target.set_ctx('store')292 if not target.can_assign():
13 unmodified lines
306307 def parse_condexpr(self):308 lineno = self.stream.current.lineno309 expr1 = self.parse_or()320 while self.stream.current.test('name:if'):321 self.stream.next()310 while self.stream.skip_if('name:if'):311 expr2 = self.parse_or()312 self.stream.expect('name:else')313 expr3 = self.parse_condexpr()314 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
2 unmodified lines
317318 def parse_or(self):319 lineno = self.stream.current.lineno320 left = self.parse_and()332 while self.stream.current.test('name:or'):333 self.stream.next()321 while self.stream.skip_if('name:or'):322 right = self.parse_and()323 left = nodes.Or(left, right, lineno=lineno)324 lineno = self.stream.current.lineno325 return left326327 def parse_and(self):328 lineno = self.stream.current.lineno329 left = self.parse_compare()342 while self.stream.current.test('name:and'):343 self.stream.next()330 while self.stream.skip_if('name:and'):331 right = self.parse_compare()332 left = nodes.And(left, right, lineno=lineno)333 lineno = self.stream.current.lineno334 return left
6 unmodified lines
341 token_type = self.stream.current.type342 if token_type in _compare_operators:343 self.stream.next()344 ops.append(nodes.Operand(token_type, self.parse_add()))358 elif self.stream.current.test('name:in'):359 self.stream.next()345 elif self.stream.skip_if('name:in'):346 ops.append(nodes.Operand('in', self.parse_add()))347 elif self.stream.current.test('name:not') and \348 self.stream.look().test('name:in'):349 self.stream.skip(2)
130 unmodified lines
480 if with_postfix:481 node = self.parse_postfix(node)482 return node483498 def parse_tuple(self, simplified=False, with_condexpr=True):484 def parse_tuple(self, simplified=False, with_condexpr=True,485 extra_end_rules=None):486 """Works like `parse_expression` but if multiple expressions are487 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.488 This method could also return a regular expression instead of a tuple489 if no commas where found.490491 The default parsing mode is a full tuple. If `simplified` is `True`492 only names and literals are parsed. The `no_condexpr` parameter is493 forwarded to :meth:`parse_expression`.494495 Because tuples do not require delimiters and may end in a bogus comma496 an extra hint is needed that marks the end of a tuple. For example497 for loops support tuples between `for` and `in`. In that case the498 `extra_end_rules` is set to ``['name:in']``.499 """500 lineno = self.stream.current.lineno501 if simplified:502 parse = lambda: self.parse_primary(with_postfix=False)
5 unmodified lines
508 is_tuple = False509 while 1:510 if args:511 self.stream.expect('comma')520 if self.is_tuple_end():512 if self.is_tuple_end(extra_end_rules):513 break514 args.append(parse())515 if self.stream.current.type is 'comma':516 is_tuple = True
244 unmodified lines