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
Provenance
- Commit
fdf9530- Tree
9e058f7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
27069d7
10 files changed+143 added−60 removed
modified:docs/cache_extension.py+1 added-1 removed
25 unmodified lines26 args = [parser.parse_expression()]27 28 # 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 linesmodified:docs/extensions.rst+2 added-2 removed
153 unmodified lines154 extensions:155 156 .. autoclass:: jinja2.parser.Parser157 :members: parse_expression, parse_tuple, parse_assign_target,158- parse_statements, skip_colon, skip_comma, free_identifier158+ parse_statements, free_identifier159 160 .. attribute:: filename161 162 The filename of the template the parser processes. This is **not**5 unmodified lines168 169 The current :class:`~jinja2.lexer.TokenStream`170 171 .. autoclass:: jinja2.lexer.TokenStream172- :members: push, look, eos, skip, next, expect172+ :members: push, look, eos, skip, next, next_if, skip_if, expect173 174 .. attribute:: current175 176 The current :class:`~jinja2.lexer.Token`.35 unmodified linesmodified:docs/index.rst+1 added
13 unmodified lines14 templates15 extensions16 integration17 switching18+ tricks19 20 changelog21 22 If you can't find the information you're looking for, have a look at the4 unmodified linesmodified:docs/templates.rst+2 added-1 removed
279 unmodified lines280 The ``{% extends %}`` tag is the key here. It tells the template engine that281 this template "extends" another template. When the template system evaluates282 this template, first it locates the parent. The extends tag should be the283 first tag in the template. Everything before it is printed out normally and284-may cause confusion.284+may cause confusion. For details about this behavior and how to take285+advantage of it, see :ref:`null-master-fallback`.286 287 The filename of the template depends on the template loader. For example the288 :class:`FileSystemLoader` allows you to access other templates by giving the289 filename. You can access templates in subdirectories with an slash::716 unmodified linesadded:docs/tricks.rst+81 added
1+Tipps and Tricks2+================3+4+.. highlight:: html+jinja5+6+This part of the documentation shows some tipps and tricks for Jinja27+templates.8+9+10+.. _null-master-fallback:11+12+Null-Master Fallback13+--------------------14+15+Jinja2 supports dynamic inheritance and does not distinguish between parent16+and child template as long as no `extends` tag is visited. While this leads17+to the surprising behavior that everything before the first `extends` tag18+including whitespace is printed out instead of being igored, it can be used19+for a neat trick.20+21+Usually child templates extend from one template that adds a basic HTML22+skeleton. However it's possible put the `extends` tag into an `if` tag to23+only extend from the layout template if the `standalone` variable evaluates24+to false which it does per default if it's not defined. Additionally a very25+basic 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::27+28+ {% 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 %}35+36+37+Alternating Rows38+----------------39+40+If you want to have different styles for each row of a table or41+list you can use the `cycle` method on the `loop` object::42+43+ <ul>44+ {% for row in rows %}45+ <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>46+ {% endfor %}47+ </ul>48+49+`cycle` can take an unlimited amount of strings. Each time this50+tag is encountered the next item from the list is rendered.51+52+53+Highlighting Active Menu Items54+------------------------------55+56+Often you want to have a navigation bar with an active navigation57+item. This is really simple to achieve. Because assignments outside58+of `block`\s in child templates are global and executed before the layout59+template is evaluated it's possible to define the active menu item in the60+child template::61+62+ {% extends "layout.html" %}63+ {% set active_page = "index" %}64+65+The layout template can then access `active_page`. Additionally it makes66+sense to defined a default for that variable::67+68+ {% 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 lines1174 visit_Not = uaop('not ')1175 del binop, uaop1176 1177 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 linesmodified:jinja2/ext.py+1 added-1 removed
143 unmodified lines144 if variables:145 parser.stream.expect('comma')146 147 # skip colon for python compatibility148- if parser.skip_colon():148+ if parser.stream.skip_if('colon'):149 break150 151 name = parser.stream.expect('name')152 if name.value in variables:211 unmodified linesmodified:jinja2/lexer.py+19 added-11 removed
217 unmodified lines218 """Got n tokens ahead."""219 for x in xrange(n):220 self.next()221 222- 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()228+229+ def skip_if(self, expr):230+ """Like `next_if` but only returns `True` or `False`."""231+ return self.next_if(expr) is not None232+233+ 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 rv244 245 def close(self):246 """Close the stream."""333 unmodified linesmodified:jinja2/nodes.py+1 added-1 removed
271 unmodified lines272 `else` block. If no else node exists it has to be an empty list.273 274 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')277 278 279 class If(Stmt):280 """If `test` is true, `body` is rendered, else `else_`."""489 unmodified linesmodified:jinja2/parser.py+33 added-41 removed
34 unmodified lines35 for tag in extension.tags:36 self.extensions[tag] = extension.parse37 self._last_identifier = 038 39- 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')44-45- 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 False46 52- 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 False58-47 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 lines94 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')99 100 # 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 lines108 109 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)127 128 def parse_if(self):129 """Parse an if construct."""130 node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)72 unmodified lines203 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 lines214 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 node220 221 def parse_signature(self, node):222 node.args = args = []2 unmodified lines225 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 lines269 self.stream.expect('comma')270 node.nodes.append(self.parse_expression())271 return node272 286- 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 lines306 307 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 lines317 318 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 left326 327 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 left6 unmodified lines341 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 lines480 if with_postfix:481 node = self.parse_postfix(node)482 return node483 498- 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.490 491 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`.494+495+ 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 lines508 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 = True244 unmodified lines