The sum filter can now sum up attributes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent bc56cd2 · Browse files · 3 files·+55 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+55 added−13 removed
- other:+55 added−13 removed
Provenance
- Commit
dd8afa2- Tree
89bfe49- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
bc56cd2
3 files changed+55 added−13 removed
modified:jinja2/testsuite/filters.py+21 added-5 removed
202 unmodified lines203 def test_sum(self):204 tmpl = env.from_string('''{{ [1, 2, 3, 4, 5, 6]|sum }}''')205 assert tmpl.render() == '21'206 207+ def test_sum_attributes(self):208+ tmpl = env.from_string('''{{ values|sum('value') }}''')209+ assert tmpl.render(values=[210+ {'value': 23},211+ {'value': 1},212+ {'value': 18},213+ ]) == '42'214+215+ def test_sum_attributes_nested(self):216+ tmpl = env.from_string('''{{ values|sum('real.value') }}''')217+ assert tmpl.render(values=[218+ {'real': {'value': 23}},219+ {'real': {'value': 1}},220+ {'real': {'value': 18}},221+ ]) == '42'222+223 def test_abs(self):224 tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''')225 assert tmpl.render() == '1|1', tmpl.render()226 22 unmodified lines249 tmpl = env.from_string('{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}')250 assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'251 252 def test_sort2(self):237- tmpl = env.from_string('{{ "".join(["c", "A", "b", "D"]|sort(false, true)) }}')253+ tmpl = env.from_string('{{ "".join(["c", "A", "b", "D"]|sort) }}')254 assert tmpl.render() == 'AbcD'255 256+ def test_sort3(self):257+ tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')258+ assert tmpl.render() == "['Bar', 'blah', 'foo']"259+260 def test_groupby(self):261 tmpl = env.from_string('''262 {%- for grouper, list in [{'foo': 1, 'bar': 2},263 {'foo': 2, 'bar': 3},61 unmodified lines325 assert tmpl.render() == '<div>foo</div>'326 tmpl = env.from_string('{{ "<div>foo</div>" }}')327 assert tmpl.render() == '<div>foo</div>'328 309- def test_sort2(self):310- tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')311- assert tmpl.render() == "['Bar', 'blah', 'foo']"329 313-330 def suite():331 suite = unittest.TestSuite()332 suite.addTest(unittest.makeSuite(FilterTestCase))333 return suitemodified:jinja2/filters.py+30 added-8 removed
46 unmodified lines47 f.environmentfilter = True48 return f49 50 51+def make_attrgetter(environment, attribute):52+ """Returns a callable that looks up the given attribute from a53+ passed object with the rules of the environment. Dots are allowed54+ to access attributes of attributes.55+ """56+ if '.' not in attribute:57+ return lambda x: environment.getitem(x, attribute)58+ attribute = attribute.split('.')59+ def attrgetter(item):60+ for part in attribute:61+ item = environment.getitem(item, part)62+ return item63+ return attrgetter64+65+66 def do_forceescape(value):67 """Enforce HTML escaping. This will probably double escape variables."""68 if hasattr(value, '__html__'):69 value = value.__html__()544 unmodified lines614 .. versionchanged:: 2.6615 It's now possible to use dotted notation to group by the child616 attribute of another attribute.617 """603- if '.' in attribute:604- def expr(item):605- for part in attribute.split('.'):606- item = environment.getitem(item, part)607- return item608- else:609- expr = lambda x: environment.getitem(x, attribute)618+ expr = make_attrgetter(environment, attribute)619 return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))620 621 622 class _GroupTuple(tuple):4 unmodified lines627 def __new__(cls, (key, value)):628 return tuple.__new__(cls, (key, list(value)))629 630 631+@environmentfilter632+def do_sum(environment, iterable, attribute=None, start=0):633+ """Sums up an iterable.634+635+ .. versionchanged:: 2.6636+ The `attribute` parameter was added to allow suming up over637+ attributes.638+ """639+ if attribute is not None:640+ iterable = imap(make_attrgetter(environment, attribute), iterable)641+ return sum(iterable, start)642+643+644 def do_list(value):645 """Convert the value into a list. If it was a string the returned list646 will be a list of characters.647 """93 unmodified lines741 'trim': do_trim,742 'striptags': do_striptags,743 'slice': do_slice,744 'batch': do_batch,723- 'sum': sum,745+ 'sum': do_sum,746 'abs': abs,747 'round': do_round,748 'groupby': do_groupby,749 'safe': do_mark_safe,2 unmodified linesmodified:CHANGES+4 added
22 unmodified lines23 the underlying Python interpreter. If you notice Jinja2 segfaulting in24 earlier versions after an upgrade of the Python interpreter you don't have25 to upgrade, it's enough to flush the bytecode cache. This just no longer26 makes this necessary, Jinja2 will automatically detect these cases now.27+- the sum filter can now sum up values by attribute. This is a backwards28+ incompatible change. The argument to the filter previously was the29+ optional starting index which defaultes to zero. This now became the30+ second argument to the function because it's rarely used.31 32 Version 2.5.533 -------------34 (re-release of 2.5.4 with built documentation removed for filesize.229 unmodified lines