Skip to content
Myr

[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

7 files+85 added−9 removed

modified:jinja/constants.py+1 added
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""111213#: list of lorem ipsum words used by the lipsum() helper function14LOREM_IPSUM_WORDS = u'''\15a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at16auctor augue bibendum blandit class commodo condimentum congue consectetuer17consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus
15 unmodified lines
modified:jinja/debugger.py+4 added-4 removed
36 unmodified lines
37"""3839import sys40from random import randrange41from opcode import opmap42from types import CodeType4142# if we have extended debugger support we should really use it43try:44 from jinja._debugger import *
106 unmodified lines
151152153class 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 """158159 def __init__(self, environment, source, filename):160 self.loader = environment.loader
5 unmodified lines
166 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 return
21 unmodified lines
modified:jinja/filters.py+36 added-2 removed
9 unmodified lines
10"""11import re12from random import choice13from urllib import urlencode, quote14from jinja.utils import urlize, escape, reversed, sorted14from jinja.utils import urlize, escape, reversed, sorted, groupby15from jinja.datastructure import TemplateData16from jinja.exceptions import FilterArgumentError1718
829 unmodified lines
848 return sorted(value, reverse=reverse)849 return wrapped850851852def do_groupby(attribute):853 """854 Group a sequence of objects by a common attribute.855856 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:860861 .. sourcecode:: html+jinja862863 <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>871872 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 wrapped883884885FILTERS = {886 'replace': do_replace,887 'upper': do_upper,888 'lower': do_lower,
38 unmodified lines
927 '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 lines
74 has_extended_debugger = True75except ImportError:76 has_extended_debugger = False7778# group by support79try:80 from itertools import groupby81except ImportError:82 class groupby(object):8384 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)8889 def __iter__(self):90 return self9192 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))9899 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)104105#: function types106callable_types = (FunctionType, MethodType)107108#: number of maximal range items
500 unmodified lines
modified:tests/runtime/exception.py+2 added-3 removed
52 unmodified lines
53 '/nested_syntax_error': u'''54{% include 'syntax_broken' %}55 ''',5657 '/code_runtime_error': u'''58{{ broken() }}59''',57 '/code_runtime_error': u'''We have a runtime error here:58 {{ broken() }}''',5960 'runtime_broken': '''\61This is an included template62{% set a = 1 / 0 %}''',
33 unmodified lines
modified:tests/test_filters.py+13 added
60 unmodified lines
61{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''62XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,63'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''64SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''65GROUPBY = '''{{ [{'foo': 1, 'bar': 2},66 {'foo': 2, 'bar': 3},67 {'foo': 1, 'bar': 1},68 {'foo': 3, 'bar': 4}]|groupby('foo') }}'''69707172def test_capitalize(env):
212 unmodified lines
285286def test_sort(env):287 tmpl = env.from_string(SORT)288 assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'289290291def 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 lines
11- fixed bug in buffet plugin regarding the package loader1213- once again improved debugger.1415- added `groupby` filter.161718Version 1.119-----------20(codename: sinka, released Jun 1, 2007)21
119 unmodified lines