Add ability to specify multiple attributes in sort,
Before adoption: this commit came in with the history the project adopted, so no landing records it.
e.g. foo|sort(attribute='name,id'). This fixes #670
authored by mayur-srivastava · committed by mayur-srivastava · parent 30685be · Browse files · 2 files·+74 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+74 added−1 removed
- tests:+33 added−0 removed
- other:+41 added−1 removed
Provenance
- Commit
8a39eca- Tree
2d4255b- Author
mayur-srivastava <mayur.p.srivastava@gmail.com>- Committer
mayur-srivastava <mayur.p.srivastava@gmail.com>- Parent
30685be
2 files changed+74 added−1 removed
modified:jinja2/filters.py+41 added-1 removed
82 unmodified lines83 84 return attrgetter85 86 87+def make_multi_attrgetter(environment, attribute, postprocess=None):88+ """Returns a callable that looks up the given comma separated89+ attributes from a passed object with the rules of the environment.90+ Dots are allowed to access attributes of each attribute. Integer91+ parts in paths are looked up as integers.92+93+ The value returned by the returned callable is a list of extracted94+ attribute values.95+96+ Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97+ """98+ def _prepare_attribute_parts(attr):99+ if attr is None:100+ return []101+ elif isinstance(attribute, string_types):102+ return [int(x) if x.isdigit() else x for x in attr.split('.')]103+ else:104+ return [attr]105+106+ attribute_parts = attribute.split(',') if isinstance(attribute, string_types) else [attribute]107+ attribute = [_prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts]108+109+ def attrgetter(item):110+ items = [None] * len(attribute)111+ for i, attribute_part in enumerate(attribute):112+ item_i = item113+ for part in attribute_part:114+ item_i = environment.getitem(item_i, part)115+116+ if postprocess is not None:117+ item_i = postprocess(item_i)118+119+ items[i] = item_i120+ return items121+122+ return attrgetter123+124+125 def do_forceescape(value):126 """Enforce HTML escaping. This will probably double escape variables."""127 if hasattr(value, '__html__'):128 value = value.__html__()178 unmodified lines307 {% endfor %}308 309 .. versionchanged:: 2.6310 The `attribute` parameter was added.311+ The attribute parameter can contain multiple comma separated312+ attributes, e.g. attr1,attr2.313 """274- key_func = make_attrgetter(314+ key_func = make_multi_attrgetter(315 environment, attribute,316 postprocess=ignore_case if not case_sensitive else None317 )318 return sorted(value, key=key_func, reverse=reverse)932 unmodified linesmodified:tests/test_filters.py+33 added
21 unmodified lines22 def __str__(self):23 return text_type(self.value)24 25 26+@implements_to_string27+class Magic2(object):28+ def __init__(self, value1, value2):29+ self.value1 = value130+ self.value2 = value231+32+ def __str__(self):33+ return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))34+35+36 @pytest.mark.filter37 class TestFilter(object):38 39 def test_filter_calling(self, env):386 unmodified lines426 def test_sort4(self, env):427 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')428 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'429 430+ def test_sort5(self, env):431+ tmpl = env.from_string('''{{ items|sort(attribute='value.0')|join }}''')432+ assert tmpl.render(items=map(Magic, [[3], [2], [4], [1]])) == '[1][2][3][4]'433+434+ def test_sort6(self, env):435+ tmpl = env.from_string('''{{ items|sort(attribute='value1,value2')|join }}''')436+ assert (tmpl.render(items=map(437+ lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]))438+ == '(2,1)(2,2)(2,5)(3,1)')439+440+ def test_sort7(self, env):441+ tmpl = env.from_string('''{{ items|sort(attribute='value2,value1')|join }}''')442+ assert (tmpl.render(items=map(lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)])) ==443+ '(2,1)(3,1)(2,2)(2,5)')444+445+ def test_sort8(self, env):446+ tmpl = env.from_string(447+ '''{{ items|sort(attribute='value1.0,value2.0')|join }}''')448+ assert (tmpl.render(items=map(449+ lambda x: Magic2(x[0], x[1]),450+ [([3], [1]), ([2], [2]), ([2], [1]), ([2], [5])]))451+ == '([2],[1])([2],[2])([2],[5])([3],[1])')452+453 def test_unique(self, env):454 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')455 assert t.render() == "bA"456 244 unmodified lines