Permalink
Browse files

Changed lookup logic for make_attrgetter to support integers like the…

… regular syntax
  • Loading branch information...
1 parent 03bea56 commit dcd0cb73120e2d924e7064933cefd3246f3cfffa @mitsuhiko mitsuhiko committed May 20, 2013
Showing with 14 additions and 2 deletions.
  1. +6 −2 jinja2/filters.py
  2. +8 −0 jinja2/testsuite/filters.py
View
@@ -54,13 +54,17 @@ def environmentfilter(f):
def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
- to access attributes of attributes.
+ to access attributes of attributes. Integer parts in paths are
+ looked up as integers.
"""
- if not isinstance(attribute, string_types) or '.' not in attribute:
+ if not isinstance(attribute, string_types) \
+ or ('.' not in attribute and not attribute.isdigit()):
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
+ if part.isdigit():
+ part = int(part)
item = environment.getitem(item, part)
return item
return attrgetter
@@ -256,6 +256,14 @@ def test_sum_attributes_nested(self):
{'real': {'value': 18}},
]) == '42'
+ def test_sum_attributes_tuple(self):
+ tmpl = env.from_string('''{{ values.items()|sum('1') }}''')
+ assert tmpl.render(values={
+ 'foo': 23,
+ 'bar': 1,
+ 'baz': 18,
+ }) == '42'
+
def test_abs(self):
tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''')
assert tmpl.render() == '1|1', tmpl.render()

0 comments on commit dcd0cb7

Please sign in to comment.