Fixed a bug with the loop context of a for loop if the iterator passed has a volatile `__len__` like the listreverseiterator. `else` in inline if-expressions is optional now.
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 c670b11 · Browse files · 7 files·+76 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+76 added−32 removed
- tests:+15 added−1 removed
- other:+61 added−31 removed
Provenance
- Commit
547d0b6- Tree
319a6ec- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c670b11
7 files changed+76 added−32 removed
modified:jinja2/compiler.py+26 added-8 removed
620 unmodified lines621 bool(frame.accesses_varargs),622 bool(frame.accesses_caller)623 ))624 625+ def position(self, node):626+ """Return a human readable position for the node."""627+ rv = 'line %d' % node.lineno628+ if self.name is not None:629+ rv += ' in' + repr(self.name)630+ return rv631+632 # -- Statement Visitors633 634 def visit_Template(self, node, frame=None):635 assert frame is None, 'no root frame allowed'205 unmodified lines841 self.indent()842 self.writeline('l_%s = environment.undefined(%r %% '843 'included_template.__name__, '844 'name=%r)' %838- (alias, 'the template %r does not export '839- 'the requested name ' + repr(name), name))845+ (alias, 'the template %%r (imported on %s) does '846+ 'not export the requested name %s' % (847+ self.position(node),848+ repr(name)849+ ), name))850 self.outdent()851 if frame.toplevel:852 var_names.append(alias)853 if not alias.startswith('_'):63 unmodified lines917 # exists.918 if 'loop' not in aliases and 'loop' in find_undeclared(919 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):920 self.writeline("l_loop = environment.undefined(%r, name='loop')" %911- "'loop' is undefined. the filter section of a loop as well " \912- "as the else block doesn't have access to the special 'loop' "913- "variable of the current loop. Because there is no parent "914- "loop it's undefined.")921+ ("'loop' is undefined. the filter section of a loop as well "922+ "as the else block doesn't have access to the special 'loop'"923+ " variable of the current loop. Because there is no parent "924+ "loop it's undefined. Happened in loop on %s" %925+ self.position(node)))926 927 self.writeline('for ', node)928 self.visit(node.target, loop_frame)929 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')410 unmodified lines1340 self.signature(node, frame)1341 self.write(')')1342 1343 def visit_CondExpr(self, node, frame):1344+ def write_expr2():1345+ if node.expr2 is not None:1346+ return self.visit(node.expr2, frame)1347+ self.write('environment.undefined(%r)' % ('the inline if-'1348+ 'expression on %s evaluated to false and '1349+ 'no else section was defined.' % self.position(node)))1350+1351 if not have_condexpr:1352 self.write('((')1353 self.visit(node.test, frame)1354 self.write(') and (')1355 self.visit(node.expr1, frame)1356 self.write(',) or (')1339- self.visit(node.expr2, frame)1357+ write_expr2()1358 self.write(',))[0]')1359 else:1360 self.write('(')1361 self.visit(node.expr1, frame)1362 self.write(' if ')1363 self.visit(node.test, frame)1364 self.write(' else ')1347- self.visit(node.expr2, frame)1365+ write_expr2()1366 self.write(')')1367 1368 def visit_Call(self, node, frame, forward_caller=False):1369 if self.environment.sandboxed:39 unmodified linesmodified:jinja2/nodes.py+5 added
497 unmodified lines498 499 def as_const(self):500 if self.test.as_const():501 return self.expr1.as_const()502+503+ # if we evaluate to an undefined object, we better do that at runtime504+ if self.expr2 is None:505+ raise Impossible()506+507 return self.expr2.as_const()508 509 510 class Filter(Expr):301 unmodified linesmodified:jinja2/parser.py+4 added-2 removed
305 unmodified lines306 lineno = self.stream.current.lineno307 expr1 = self.parse_or()308 while self.stream.skip_if('name:if'):309 expr2 = self.parse_or()310- self.stream.expect('name:else')311- expr3 = self.parse_condexpr()310+ if self.stream.skip_if('name:else'):311+ expr3 = self.parse_condexpr()312+ else:313+ expr3 = None314 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)315 lineno = self.stream.current.lineno316 return expr1317 456 unmodified linesmodified:jinja2/runtime.py+20 added-20 removed
195 unmodified lines196 197 class LoopContext(object):198 """A loop context for dynamic iteration."""199 200- def __init__(self, iterable, enforce_length=False, recurse=None):201- self._iterable = iterable202- self._next = iter(iterable).next203- self._length = None200+ def __init__(self, iterable, recurse=None):201+ self._iterator = iter(iterable)202 self._recurse = recurse203 self.index0 = -1206- if enforce_length:207- len(self)204 205+ # try to get the length of the iterable early. This must be done206+ # here because there are some broken iterators around where there207+ # __len__ is the number of iterations left (i'm looking at your208+ # listreverseiterator!).209+ try:210+ self._length = len(iterable)211+ except (TypeError, AttributeError):212+ self._length = None213+214 def cycle(self, *args):215 """Cycles among the arguments with the current loop index."""216 if not args:217 raise TypeError('no items for cycling given')218 return args[self.index0 % len(args)]219 220 first = property(lambda x: x.index0 == 0)216- last = property(lambda x: x.revindex0 == 0)221+ last = property(lambda x: x.index0 + 1 == x.length)222 index = property(lambda x: x.index0 + 1)223 revindex = property(lambda x: x.length - x.index0)224 revindex0 = property(lambda x: x.length - x.index)225 15 unmodified lines241 242 @property243 def length(self):244 if self._length is None:240- try:241- # first try to get the length from the iterable (if the242- # iterable is a sequence)243- length = len(self._iterable)244- except TypeError:245- # if that's not possible (ie: iterating over a generator)246- # we have to convert the iterable into a sequence and247- # use the length of that.248- self._iterable = tuple(self._iterable)249- self._next = iter(self._iterable).next250- length = len(tuple(self._iterable)) + self.index0 + 1251- self._length = length245+ # if was not possible to get the length of the iterator when246+ # the loop context was created (ie: iterating over a generator)247+ # we have to convert the iterable into a sequence and use the248+ # length of that.249+ iterable = tuple(self._iterator)250+ self._iterator = iter(iterable)251+ self._length = len(iterable) + self.index0 + 1252 return self._length253 254 def __repr__(self):255 return '<%s %r/%r>' % (15 unmodified lines271 272 def next(self):273 ctx = self.context274 ctx.index0 += 1275- return ctx._next(), ctx275+ return ctx._iterator.next(), ctx276 277 278 class Macro(object):279 """Wraps a macro."""180 unmodified linesmodified:tests/test_forloop.py+6 added
114 unmodified lines115 tmpl = env.from_string(LOOPLOOP)116 assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'117 118 119+def test_reversed_bug(env):120+ tmpl = env.from_string('{% for i in items %}{{ i }}{% if not loop.last %}'121+ ',{% endif %}{% endfor %}')122+ assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'123+124+125 def test_loop_errors(env):126 tmpl = env.from_string(LOOPERROR1)127 raises(UndefinedError, tmpl.render)128 tmpl = env.from_string(LOOPERROR2)12 unmodified linesmodified:tests/test_syntax.py+9 added-1 removed
6 unmodified lines7 :license: BSD, see LICENSE for more details.8 """9 from py.test import raises10 from jinja2 import Environment, DictLoader11-from jinja2.exceptions import TemplateSyntaxError11+from jinja2.exceptions import TemplateSyntaxError, UndefinedError12 13 14 CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''15 SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''107 unmodified lines123 tmpl = env.from_string(CONDEXPR)124 assert tmpl.render() == '0'125 126 127+def test_short_conditional_expression(env):128+ tmpl = env.from_string('<{{ 1 if false }}>')129+ assert tmpl.render() == '<>'130+131+ tmpl = env.from_string('<{{ (1 if false).bar }}>')132+ raises(UndefinedError, tmpl.render)133+134+135 def test_filter_priority(env):136 tmpl = env.from_string(FILTERPRIORITY)137 assert tmpl.render() == 'FOOBAR'138 53 unmodified linesmodified:CHANGES+6 added-1 removed
17 unmodified lines18 data and something similar.19 20 - added :meth:`jinja2.environment.TemplateStream.dump`.21 22-- added support for implicit string literal concatenation.22+- added missing support for implicit string literal concatenation.23 ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}``24 25+- `else` is optional for conditional expressions. If not given it evaluates26+ to `false`.27+28+- improved error reporting for undefined values by providing a position.29+30 Version 2.0rc131 --------------32 (no codename, released on June 9th 2008)33 1 unmodified line