Merge pull request #1013 from mayuropensource/jinja-670-sort-multi-attr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add ability to specify multiple attributes in sort
authored by Kevin Brown · committed by GitHub · parents 6ffe6cc, 5dea3f7 · Browse files · 2 files·+76 added−7 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+76 added−7 removed
- tests:+33 added−0 removed
- other:+43 added−7 removed
Provenance
- Commit
321b499- Tree
a2adedb- Author
Kevin Brown <kevin-brown@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6ffe6cc- Parent 2
5dea3f7
2 files changed+76 added−7 removed
modified:jinja2/filters.py+43 added-7 removed
63 unmodified lines64 passed object with the rules of the environment. Dots are allowed65 to access attributes of attributes. Integer parts in paths are66 looked up as integers.67 """68- if attribute is None:69- attribute = []70- elif isinstance(attribute, string_types):71- attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]72- else:73- attribute = [attribute]68+ attribute = _prepare_attribute_parts(attribute)69 70 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)5 unmodified lines78 79 return attrgetter80 81 82+def make_multi_attrgetter(environment, attribute, postprocess=None):83+ """Returns a callable that looks up the given comma separated84+ attributes from a passed object with the rules of the environment.85+ Dots are allowed to access attributes of each attribute. Integer86+ parts in paths are looked up as integers.87+88+ The value returned by the returned callable is a list of extracted89+ attribute values.90+91+ Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.92+ """93+ attribute_parts = attribute.split(',') if isinstance(attribute, string_types) else [attribute]94+ attribute = [_prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts]95+96+ def attrgetter(item):97+ items = [None] * len(attribute)98+ for i, attribute_part in enumerate(attribute):99+ item_i = item100+ for part in attribute_part:101+ item_i = environment.getitem(item_i, part)102+103+ if postprocess is not None:104+ item_i = postprocess(item_i)105+106+ items[i] = item_i107+ return items108+109+ return attrgetter110+111+112+def _prepare_attribute_parts(attr):113+ if attr is None:114+ return []115+ elif isinstance(attr, string_types):116+ return [int(x) if x.isdigit() else x for x in attr.split('.')]117+ else:118+ return [attr]119+120+121 def do_forceescape(value):122 """Enforce HTML escaping. This will probably double escape variables."""123 if hasattr(value, '__html__'):124 value = value.__html__()178 unmodified lines303 {% endfor %}304 305 .. versionchanged:: 2.6306 The `attribute` parameter was added.307+ The attribute parameter can contain multiple comma separated308+ attributes, e.g. attr1,attr2.309 """274- key_func = make_attrgetter(310+ key_func = make_multi_attrgetter(311 environment, attribute,312 postprocess=ignore_case if not case_sensitive else None313 )314 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