Commit 50deed80 by Chris Jerdonek

Merge pull request #93 "Allows to use generators just like lists/tuples"

From: https://github.com/lucasb-eyer/pystache/commit/dd9184bb05d0b1001b30d61a0202de1273543316
Into: 'issue-93'

Objects that support iteration (i.e. implement __iter__), aside from
dictionaries, now behave like lists.
parents f7df3412 dd9184bb
......@@ -168,7 +168,7 @@ class RenderEngine(object):
template = data(template)
parsed_template = self._parse(template, delimiters=delims)
data = [ data ]
elif type(data) not in [list, tuple]:
elif not hasattr(data, '__iter__') or isinstance(data, dict):
data = [ data ]
parts = []
......
......@@ -376,6 +376,29 @@ class RenderTests(unittest.TestCase):
context = {'test': (lambda text: 'Hi %s' % text)}
self._assert_render('Hi Mom', template, context)
def test_section__iterable(self):
"""
Check that objects supporting iteration (aside from dicts) behave like lists.
"""
template = '{{#iterable}}{{.}}{{/iterable}}'
context = {'iterable': (i for i in range(3))} # type 'generator'
self._assert_render('012', template, context)
context = {'iterable': xrange(4)} # type 'xrange'
self._assert_render('0123', template, context)
d = {'foo': 0, 'bar': 0}
# We don't know what order of keys we'll be given, but from the
# Python documentation:
# "If items(), keys(), values(), iteritems(), iterkeys(), and
# itervalues() are called with no intervening modifications to
# the dictionary, the lists will directly correspond."
expected = ''.join(d.keys())
context = {'iterable': d.iterkeys()} # type 'dictionary-keyiterator'
self._assert_render(expected, template, context)
def test_section__lambda__tag_in_output(self):
"""
Check that callable output is treated as a template string (issue #46).
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment