From 6dba4d66724594abdfcf49ae31aded29ebf6d304 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Mon, 21 May 2007 23:41:36 +0200 Subject: [PATCH] [svn] checked in changes regarding variable length iteration --HG-- branch : trunk --- CHANGES | 4 ++++ jinja/datastructure.py | 9 ++++++++- tests/test_forloop.py | 10 ++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) 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' -- 2.26.2