[svn] added groupby filter and fixed some small bugs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 61dc5c2 · Browse files · 7 files·+85 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+85 added−9 removed
- tests:+15 added−3 removed
- other:+70 added−6 removed
Provenance
- Commit
e39a5d2- Tree
905a58c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
61dc5c2
7 files changed+85 added−9 removed
modified:jinja/constants.py+1 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 13+#: list of lorem ipsum words used by the lipsum() helper function14 LOREM_IPSUM_WORDS = u'''\15 a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at16 auctor augue bibendum blandit class commodo condimentum congue consectetuer17 consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus15 unmodified linesmodified:jinja/debugger.py+4 added-4 removed
36 unmodified lines37 """38 39 import sys40 from random import randrange41-from opcode import opmap42-from types import CodeType41 42 # if we have extended debugger support we should really use it43 try:44 from jinja._debugger import *106 unmodified lines151 152 153 class TracebackLoader(object):154 """157- Fake importer that just returns the source of a template.155+ Fake importer that just returns the source of a template. It's just used156+ by Jinja interally and you shouldn't use it on your own.157 """158 159 def __init__(self, environment, source, filename):160 self.loader = environment.loader5 unmodified lines166 Hacky way to let traceback systems know about the167 Jinja template sourcecode. Very hackish indeed.168 """169 # check for linecache, not every implementation of python171- # might have such an module.170+ # might have such an module (this check is pretty senseless171+ # because we depend on cpython anway)172 try:173 from linecache import cache174 except ImportError:175 return21 unmodified linesmodified:jinja/filters.py+36 added-2 removed
9 unmodified lines10 """11 import re12 from random import choice13 from urllib import urlencode, quote14-from jinja.utils import urlize, escape, reversed, sorted14+from jinja.utils import urlize, escape, reversed, sorted, groupby15 from jinja.datastructure import TemplateData16 from jinja.exceptions import FilterArgumentError17 18 829 unmodified lines848 return sorted(value, reverse=reverse)849 return wrapped850 851 852+def do_groupby(attribute):853+ """854+ Group a sequence of objects by a common attribute.855+856+ If you for example have a list of dicts or objects that represent persons857+ with `gender`, `first_name` and `last_name` attributes and you want to858+ group all users by genders you can do something like the following859+ snippet:860+861+ .. sourcecode:: html+jinja862+863+ <ul>864+ {% for group in persons|groupby('gender') %}865+ <li>{{ group.grouper }}<ul>866+ {% for person in group.list %}867+ <li>{{ person.first_name }} {{ person.last_name }}</li>868+ {% endfor %}</ul></li>869+ {% endfor %}870+ </ul>871+872+ As you can see the item we're grouping by is stored in the `grouper`873+ attribute and the `list` contains all the objects that have this grouper874+ in common.875+ """876+ def wrapped(env, context, value):877+ expr = lambda x: env.get_attribute(x, attribute)878+ return [{879+ 'grouper': a,880+ 'list': list(b)881+ } for a, b in groupby(sorted(value, key=expr), expr)]882+ return wrapped883+884+885 FILTERS = {886 'replace': do_replace,887 'upper': do_upper,888 'lower': do_lower,38 unmodified lines927 'batch': do_batch,928 'sum': do_sum,929 'abs': do_abs,930 'round': do_round,898- 'sort': do_sort931+ 'sort': do_sort,932+ 'groupby': do_groupby933 }modified:jinja/utils.py+27 added
73 unmodified lines74 has_extended_debugger = True75 except ImportError:76 has_extended_debugger = False77 78+# group by support79+try:80+ from itertools import groupby81+except ImportError:82+ class groupby(object):83+84+ def __init__(self, iterable, key=lambda x: x):85+ self.keyfunc = key86+ self.it = iter(iterable)87+ self.tgtkey = self.currkey = self.currvalue = xrange(0)88+89+ def __iter__(self):90+ return self91+92+ def next(self):93+ while self.currkey == self.tgtkey:94+ self.currvalue = self.it.next()95+ self.currkey = self.keyfunc(self.currvalue)96+ self.tgtkey = self.currkey97+ return (self.currkey, self._grouper(self.tgtkey))98+99+ def _grouper(self, tgtkey):100+ while self.currkey == tgtkey:101+ yield self.currvalue102+ self.currvalue = self.it.next()103+ self.currkey = self.keyfunc(self.currvalue)104+105 #: function types106 callable_types = (FunctionType, MethodType)107 108 #: number of maximal range items500 unmodified linesmodified:tests/runtime/exception.py+2 added-3 removed
52 unmodified lines53 '/nested_syntax_error': u'''54 {% include 'syntax_broken' %}55 ''',56 57- '/code_runtime_error': u'''58-{{ broken() }}59-''',57+ '/code_runtime_error': u'''We have a runtime error here:58+ {{ broken() }}''',59 60 'runtime_broken': '''\61 This is an included template62 {% set a = 1 / 0 %}''',33 unmodified linesmodified:tests/test_filters.py+13 added
60 unmodified lines61 {{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''62 XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,63 'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''64 SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''65+GROUPBY = '''{{ [{'foo': 1, 'bar': 2},66+ {'foo': 2, 'bar': 3},67+ {'foo': 1, 'bar': 1},68+ {'foo': 3, 'bar': 4}]|groupby('foo') }}'''69 70 71 72 def test_capitalize(env):212 unmodified lines285 286 def test_sort(env):287 tmpl = env.from_string(SORT)288 assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'289+290+291+def test_groupby(env):292+ tmpl = env.from_string(GROUPBY)293+ assert tmpl.render() == (294+ "[{'list': [{'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}], "295+ "'grouper': 1}, {'list': [{'foo': 2, 'bar': 3}], 'grouper': 2}, "296+ "{'list': [{'foo': 3, 'bar': 4}], 'grouper': 3}]"297+ )modified:CHANGES+2 added
10 unmodified lines11 - fixed bug in buffet plugin regarding the package loader12 13 - once again improved debugger.14 15+- added `groupby` filter.16 17+18 Version 1.119 -----------20 (codename: sinka, released Jun 1, 2007)21 119 unmodified lines