add items filter
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by David Lord · parent d5b8f66 · Browse files · 3 files·+43 added−0 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+43 added−0 removed
- tests:+11 added−0 removed
- other:+32 added−0 removed
Provenance
- Commit
1c036ca- Tree
273500f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
David Lord <davidism@gmail.com>- Parent
d5b8f66
3 files changed+43 added−0 removed
modified:src/jinja2/filters.py+31 added
216 unmodified lines217 """Convert a value to lowercase."""218 return soft_str(s).lower()219 220 221+def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:222+ """Return an iterator over the ``(key, value)`` items of a mapping.223+224+ ``x|items`` is the same as ``x.items()``, except if ``x`` is225+ undefined an empty iterator is returned.226+227+ This filter is useful if you expect the template to be rendered with228+ an implementation of Jinja in another programming language that does229+ not have a ``.items()`` method on its mapping type.230+231+ .. code-block:: html+jinja232+233+ <dl>234+ {% for key, value in my_dict|items %}235+ <dt>{{ key }}236+ <dd>{{ value }}237+ {% endfor %}238+ </dl>239+240+ .. versionadded:: 3.1241+ """242+ if isinstance(value, Undefined):243+ return244+245+ if not isinstance(value, abc.Mapping):246+ raise TypeError("Can only get item pairs from a mapping.")247+248+ yield from value.items()249+250+251 @pass_eval_context252 def do_xmlattr(253 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True254 ) -> str:1513 unmodified lines1768 "last": do_last,1769 "length": len,1770 "list": do_list,1771 "lower": do_lower,1772+ "items": do_items,1773 "map": do_map,1774 "min": do_min,1775 "max": do_max,1776 "pprint": do_pprint,26 unmodified linesmodified:tests/test_filters.py+11 added
249 unmodified lines250 tmpl = env.from_string("""{{ "FOO"|lower }}""")251 out = tmpl.render()252 assert out == "foo"253 254+ def test_items(self, env):255+ d = {i: c for i, c in enumerate("abc")}256+ tmpl = env.from_string("""{{ d|items|list }}""")257+ out = tmpl.render(d=d)258+ assert out == "[(0, 'a'), (1, 'b'), (2, 'c')]"259+260+ def test_items_undefined(self, env):261+ tmpl = env.from_string("""{{ d|items|list }}""")262+ out = tmpl.render()263+ assert out == "[]"264+265 def test_pprint(self, env):266 from pprint import pformat267 268 tmpl = env.from_string("""{{ data|pprint }}""")586 unmodified linesmodified:CHANGES.rst+1 added
28 unmodified lines29 - Update valid identifier characters from Python 3.6 to 3.7.30 :pr:`1571`31 - Filters and tests decorated with ``@async_variant`` are pickleable.32 :pr:`1612`33+- Add ``items`` filter. :issue:`1561`34 35 36 Version 3.0.337 -------------911 unmodified lines