From: Armin Ronacher Date: Mon, 21 May 2007 21:41:36 +0000 (+0200) Subject: [svn] checked in changes regarding variable length iteration X-Git-Tag: 2.0rc1~320 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=6dba4d66724594abdfcf49ae31aded29ebf6d304;p=jinja2.git [svn] checked in changes regarding variable length iteration --HG-- branch : trunk --- diff --git a/CHANGES b/CHANGES index bda176c..dd45ed0 100644 --- a/CHANGES +++ b/CHANGES @@ -99,6 +99,10 @@ Version 1.1 be an expression. As soon as you specify an expression as second argument the closing tag has to be omitted. +- It's now possible to iterate over iterators additionally to sequences. + If the iterator is inifite it will crash however, so makes sure you don't + pass something like that to a template! + Version 1.0 ----------- diff --git a/jinja/datastructure.py b/jinja/datastructure.py index daa2e27..22864b5 100644 --- a/jinja/datastructure.py +++ b/jinja/datastructure.py @@ -326,10 +326,17 @@ class LoopContext(object): """ if seq in (Undefined, None): seq = () + length = 0 + else: + try: + length = len(seq) + except TypeError: + seq = list(seq) + length = len(seq) self._stack.append({ 'index': -1, 'seq': seq, - 'length': len(seq) + 'length': length }) return self diff --git a/tests/test_forloop.py b/tests/test_forloop.py index af8afce..ca50020 100644 --- a/tests/test_forloop.py +++ b/tests/test_forloop.py @@ -17,6 +17,7 @@ CONTEXTVARS = '''{% for item in seq %}\ CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\ {% for item in seq %}{% cycle through %}{% endfor %}''' SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}''' +VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}''' def test_simple(env): @@ -63,3 +64,12 @@ def test_scope(env): tmpl = env.from_string(SCOPE) output = tmpl.render(seq=range(10)) assert not output + + +def test_varlen(env): + def inner(): + for item in range(5): + yield item + tmpl = env.from_string(VARLEN) + output = tmpl.render(iter=inner()) + assert output == '01234'