Skip to content
Myr

filters.py

This file

Path

src/jinja2/filters.py

1,867 lines · 53.3 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

History of this file

Take it

The walk stopped after 200 commits: lines older than c580dd0 point at it.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1why, one step back
1"""Built-in template filters used with the ``|`` operator."""

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 2why, one step back
2

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 3–5why, one step back
3import math
4import random5import re

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 6–7why, one step back
6import typing
7import typing as t

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 8why, one step back
8from collections import abc

Merge branch 'stable'David Lordbefore adoption220e67a

line 9why, one step back
9from inspect import getattr_static

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 10–16why, one step back
10from itertools import chain
11from itertools import groupby1213from markupsafe import escape14from markupsafe import Markup15from markupsafe import soft_str16

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 17–20why, one step back
17from .async_utils import async_variant
18from .async_utils import auto_aiter19from .async_utils import auto_await20from .async_utils import auto_to_list

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 21–23why, one step back
21from .exceptions import FilterArgumentError
22from .runtime import Undefined23from .utils import htmlsafe_json_dumps

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

lines 24–26why, one step back
24from .utils import pass_context
25from .utils import pass_environment26from .utils import pass_eval_context

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 27–30why, one step back
27from .utils import pformat
28from .utils import url_quote29from .utils import urlize30

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 31–32why, one step back
31if t.TYPE_CHECKING:
32 import typing_extensions as te

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 33why, one step back
33

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 34–37why, one step back
34 from .environment import Environment
35 from .nodes import EvalContext36 from .runtime import Context37 from .sandbox import SandboxedEnvironment # noqa: F401

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 38why, one step back
38

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 39–43why, one step back
39 class HasHTML(te.Protocol):
40 def __html__(self) -> str:41 pass4243

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 44–46why, one step back
44F = t.TypeVar("F", bound=t.Callable[..., t.Any])
45K = t.TypeVar("K")46V = t.TypeVar("V")

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 47–48why, one step back
47
48

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 49why, one step back
49def ignore_case(value: V) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 50–51why, one step back
50 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings
51 to lowercase and returns other types as-is."""

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 52why, one step back
52 if isinstance(value, str):

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 53why, one step back
53 return t.cast(V, value.lower())

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 54why, one step back
54

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 55why, one step back
55 return value

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 56why, one step back
56

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 57–59why, one step back
57
58def make_attrgetter(59 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 60–62why, one step back
60 attribute: str | int | None,
61 postprocess: t.Callable[[t.Any], t.Any] | None = None,62 default: t.Any | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 63why, one step back
63) -> t.Callable[[t.Any], t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 64–68why, one step back
64 """Returns a callable that looks up the given attribute from a
65 passed object with the rules of the environment. Dots are allowed66 to access attributes of attributes. Integer parts in paths are67 looked up as integers.68 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 69why, one step back
69 parts = _prepare_attribute_parts(attribute)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 70why, one step back
70

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 71–72why, one step back
71 def attrgetter(item: t.Any) -> t.Any:
72 for part in parts:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 73–74why, one step back
73 item = environment.getitem(item, part)
74

Merge pull request #1356 from BALaka-18/map-filter-defaultDavid Lordbefore adoption8ab9db2

line 75why, one step back
75 if default is not None and isinstance(item, Undefined):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 76–85why, one step back
76 item = default
7778 if postprocess is not None:79 item = postprocess(item)8081 return item8283 return attrgetter8485

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 86–87why, one step back
86def make_multi_attrgetter(
87 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 88–89why, one step back
88 attribute: str | int | None,
89 postprocess: t.Callable[[t.Any], t.Any] | None = None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 90why, one step back
90) -> t.Callable[[t.Any], list[t.Any]]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 91–100why, one step back
91 """Returns a callable that looks up the given comma separated
92 attributes from a passed object with the rules of the environment.93 Dots are allowed to access attributes of each attribute. Integer94 parts in paths are looked up as integers.9596 The value returned by the returned callable is a list of extracted97 attribute values.9899 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.100 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 101why, one step back
101 if isinstance(attribute, str):

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 102why, one step back
102 split: t.Sequence[str | int | None] = attribute.split(",")

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 103–104why, one step back
103 else:
104 split = [attribute]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 105why, one step back
105

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 106–107why, one step back
106 parts = [_prepare_attribute_parts(item) for item in split]
107

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 108why, one step back
108 def attrgetter(item: t.Any) -> list[t.Any]:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 109–111why, one step back
109 items = [None] * len(parts)
110111 for i, attribute_part in enumerate(parts):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 112why, one step back
112 item_i = item

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 113why, one step back
113

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 114–120why, one step back
114 for part in attribute_part:
115 item_i = environment.getitem(item_i, part)116117 if postprocess is not None:118 item_i = postprocess(item_i)119120 items[i] = item_i

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 121why, one step back
121

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 122–126why, one step back
122 return items
123124 return attrgetter125126

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 127why, one step back
127def _prepare_attribute_parts(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 128–129why, one step back
128 attr: str | int | None,
129) -> list[str | int]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 130–131why, one step back
130 if attr is None:
131 return []

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 132–133why, one step back
132
133 if isinstance(attr, str):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 134–135why, one step back
134 return [int(x) if x.isdigit() else x for x in attr.split(".")]
135

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 136why, one step back
136 return [attr]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 137why, one step back
137

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 138why, one step back
138

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 139why, one step back
139def do_forceescape(value: "str | HasHTML") -> Markup:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 140–141why, one step back
140 """Enforce HTML escaping. This will probably double escape variables."""
141 if hasattr(value, "__html__"):

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 142–143why, one step back
142 value = t.cast("HasHTML", value).__html__()
143

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 144–146why, one step back
144 return escape(str(value))
145146

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 147why, one step back
147def do_urlencode(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 148why, one step back
148 value: str | t.Mapping[str, t.Any] | t.Iterable[tuple[str, t.Any]],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 149why, one step back
149) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 150–168why, one step back
150 """Quote data for use in a URL path or query using UTF-8.
151152 Basic wrapper around :func:`urllib.parse.quote` when given a153 string, or :func:`urllib.parse.urlencode` for a dict or iterable.154155 :param value: Data to quote. A string will be quoted directly. A156 dict or iterable of ``(key, value)`` pairs will be joined as a157 query string.158159 When given a string, "/" is not quoted. HTTP servers treat "/" and160 "%2F" equivalently in paths. If you need quoted slashes, use the161 ``|replace("/", "%2F")`` filter.162163 .. versionadded:: 2.7164 """165 if isinstance(value, str) or not isinstance(value, abc.Iterable):166 return url_quote(value)167168 if isinstance(value, dict):

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 169why, one step back
169 items: t.Iterable[tuple[str, t.Any]] = value.items()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 170why, one step back
170 else:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 171why, one step back
171 items = value # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 172–177why, one step back
172
173 return "&".join(174 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items175 )176177

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 178why, one step back
178@pass_eval_context

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 179why, one step back
179def do_replace(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 180why, one step back
180 eval_ctx: "EvalContext", s: str, old: str, new: str, count: int | None = None

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 181why, one step back
181) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 182–197why, one step back
182 """Return a copy of the value with all occurrences of a substring
183 replaced with a new one. The first argument is the substring184 that should be replaced, the second is the replacement string.185 If the optional third argument ``count`` is given, only the first186 ``count`` occurrences are replaced:187188 .. sourcecode:: jinja189190 {{ "Hello World"|replace("Hello", "Goodbye") }}191 -> Goodbye World192193 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}194 -> d'oh, d'oh, aaargh195 """196 if count is None:197 count = -1

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 198why, one step back
198

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 199–200why, one step back
199 if not eval_ctx.autoescape:
200 return str(s).replace(str(old), str(new), count)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 201why, one step back
201

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 202–209why, one step back
202 if (
203 hasattr(old, "__html__")204 or hasattr(new, "__html__")205 and not hasattr(s, "__html__")206 ):207 s = escape(s)208 else:209 s = soft_str(s)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 210why, one step back
210

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 211–213why, one step back
211 return s.replace(soft_str(old), soft_str(new), count)
212213

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 214why, one step back
214def do_upper(s: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 215–218why, one step back
215 """Convert a value to uppercase."""
216 return soft_str(s).upper()217218

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 219why, one step back
219def do_lower(s: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 220–223why, one step back
220 """Convert a value to lowercase."""
221 return soft_str(s).lower()222223

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 224why, one step back
224def do_items(value: t.Mapping[K, V] | Undefined) -> t.Iterator[tuple[K, V]]:

Merge pull request #1564 from pallets/feature/pairsDavid Lordbefore adoptiona819eb3

lines 225–253why, one step back
225 """Return an iterator over the ``(key, value)`` items of a mapping.
226227 ``x|items`` is the same as ``x.items()``, except if ``x`` is228 undefined an empty iterator is returned.229230 This filter is useful if you expect the template to be rendered with231 an implementation of Jinja in another programming language that does232 not have a ``.items()`` method on its mapping type.233234 .. code-block:: html+jinja235236 <dl>237 {% for key, value in my_dict|items %}238 <dt>{{ key }}239 <dd>{{ value }}240 {% endfor %}241 </dl>242243 .. versionadded:: 3.1244 """245 if isinstance(value, Undefined):246 return247248 if not isinstance(value, abc.Mapping):249 raise TypeError("Can only get item pairs from a mapping.")250251 yield from value.items()252253

Merge branch '3.1.x'David Lordbefore adoption11550f9

lines 254–256why, one step back
254# Check for characters that would move the parser state from key to value.
255# https://html.spec.whatwg.org/#attribute-name-state256_attr_key_re = re.compile(r"[\s/>=]", flags=re.ASCII)

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

lines 257–258why, one step back
257
258

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 259why, one step back
259@pass_eval_context

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 260–262why, one step back
260def do_xmlattr(
261 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True262) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 263–264why, one step back
263 """Create an SGML/XML attribute string based on the items in a dict.
264

Merge branch '3.1.x'David Lordbefore adoption11550f9

lines 265–266why, one step back
265 **Values** that are neither ``none`` nor ``undefined`` are automatically
266 escaped, safely allowing untrusted user input.

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

line 267why, one step back
267

Merge branch '3.1.x'David Lordbefore adoption11550f9

lines 268–273why, one step back
268 User input should not be used as **keys** to this filter. If any key
269 contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals270 sign, this fails with a ``ValueError``. Regardless of this, user input271 should never be used as keys to this filter, or must be separately validated272 first.273

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 274–290why, one step back
274 .. sourcecode:: html+jinja
275276 <ul{{ {'class': 'my_list', 'missing': none,277 'id': 'list-%d'|format(variable)}|xmlattr }}>278 ...279 </ul>280281 Results in something like this:282283 .. sourcecode:: html284285 <ul class="my_list" id="list-42">286 ...287 </ul>288289 As you can see it automatically prepends a space in front of the item290 if the filter returned something unless the second parameter is false.

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

line 291why, one step back
291

Merge branch '3.1.x'David Lordbefore adoption11550f9

lines 292–295why, one step back
292 .. versionchanged:: 3.1.4
293 Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign294 are not allowed.295

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

lines 296–297why, one step back
296 .. versionchanged:: 3.1.3
297 Keys with spaces are not allowed.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 298why, one step back
298 """

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

lines 299–304why, one step back
299 items = []
300301 for key, value in d.items():302 if value is None or isinstance(value, Undefined):303 continue304

Merge branch '3.1.x'David Lordbefore adoption11550f9

lines 305–306why, one step back
305 if _attr_key_re.search(key) is not None:
306 raise ValueError(f"Invalid character in attribute name: {key!r}")

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

lines 307–310why, one step back
307
308 items.append(f'{escape(key)}="{escape(value)}"')309310 rv = " ".join(items)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 311why, one step back
311

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 312–313why, one step back
312 if autospace and rv:
313 rv = " " + rv

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 314–315why, one step back
314
315 if eval_ctx.autoescape:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 316why, one step back
316 rv = Markup(rv)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 317why, one step back
317

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 318–320why, one step back
318 return rv
319320

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 321why, one step back
321def do_capitalize(s: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 322–327why, one step back
322 """Capitalize a value. The first character will be uppercase, all others
323 lowercase.324 """325 return soft_str(s).capitalize()326327

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 328–331why, one step back
328_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
329330331def do_title(s: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 332–343why, one step back
332 """Return a titlecased version of the value. I.e. words will start with
333 uppercase letters, all remaining characters are lowercase.334 """335 return "".join(336 [337 item[0].upper() + item[1:].lower()338 for item in _word_beginning_split_re.split(soft_str(s))339 if item340 ]341 )342343

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 344why, one step back
344def do_dictsort(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 345why, one step back
345 value: t.Mapping[K, V],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 346–348why, one step back
346 case_sensitive: bool = False,
347 by: 'te.Literal["key", "value"]' = "key",348 reverse: bool = False,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 349why, one step back
349) -> list[tuple[K, V]]:

Merge pull request #1236 from sixtyfathoms/fix/issue-1184David Lordbefore adoptione45eabc

lines 350–351why, one step back
350 """Sort a dict and yield (key, value) pairs. Python dicts may not
351 be in the order you want to display them in, so sort them first.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 352–373why, one step back
352
353 .. sourcecode:: jinja354355 {% for key, value in mydict|dictsort %}356 sort the dict by key, case insensitive357358 {% for key, value in mydict|dictsort(reverse=true) %}359 sort the dict by key, case insensitive, reverse order360361 {% for key, value in mydict|dictsort(true) %}362 sort the dict by key, case sensitive363364 {% for key, value in mydict|dictsort(false, 'value') %}365 sort the dict by value, case insensitive366 """367 if by == "key":368 pos = 0369 elif by == "value":370 pos = 1371 else:372 raise FilterArgumentError('You can only sort by either "key" or "value"')373

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 374why, one step back
374 def sort_func(item: tuple[t.Any, t.Any]) -> t.Any:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 375–384why, one step back
375 value = item[pos]
376377 if not case_sensitive:378 value = ignore_case(value)379380 return value381382 return sorted(value.items(), key=sort_func, reverse=reverse)383384

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 385why, one step back
385@pass_environment

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 386–390why, one step back
386def do_sort(
387 environment: "Environment",388 value: "t.Iterable[V]",389 reverse: bool = False,390 case_sensitive: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 391why, one step back
391 attribute: str | int | None = None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 392why, one step back
392) -> "list[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 393–423why, one step back
393 """Sort an iterable using Python's :func:`sorted`.
394395 .. sourcecode:: jinja396397 {% for city in cities|sort %}398 ...399 {% endfor %}400401 :param reverse: Sort descending instead of ascending.402 :param case_sensitive: When sorting strings, sort upper and lower403 case separately.404 :param attribute: When sorting objects or dicts, an attribute or405 key to sort by. Can use dot notation like ``"address.city"``.406 Can be a list of attributes like ``"age,name"``.407408 The sort is stable, it does not change the relative order of409 elements that compare equal. This makes it is possible to chain410 sorts on different attributes and ordering.411412 .. sourcecode:: jinja413414 {% for user in users|sort(attribute="name")415 |sort(reverse=true, attribute="age") %}416 ...417 {% endfor %}418419 As a shortcut to chaining when the direction is the same for all420 attributes, pass a comma separate list of attributes.421422 .. sourcecode:: jinja423

Merge branch '3.0.x'David Lordbefore adoption896a621

line 424why, one step back
424 {% for user in users|sort(attribute="age,name") %}

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 425–440why, one step back
425 ...
426 {% endfor %}427428 .. versionchanged:: 2.11.0429 The ``attribute`` parameter can be a comma separated list of430 attributes, e.g. ``"age,name"``.431432 .. versionchanged:: 2.6433 The ``attribute`` parameter was added.434 """435 key_func = make_multi_attrgetter(436 environment, attribute, postprocess=ignore_case if not case_sensitive else None437 )438 return sorted(value, key=key_func, reverse=reverse)439440

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 441why, one step back
441@pass_environment

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 442why, one step back
442def sync_do_unique(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 443–445why, one step back
443 environment: "Environment",
444 value: "t.Iterable[V]",445 case_sensitive: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 446why, one step back
446 attribute: str | int | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 447why, one step back
447) -> "t.Iterator[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 448–473why, one step back
448 """Returns a list of unique items from the given iterable.
449450 .. sourcecode:: jinja451452 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}453 -> ['foo', 'bar', 'foobar']454455 The unique items are yielded in the same order as their first occurrence in456 the iterable passed to the filter.457458 :param case_sensitive: Treat upper and lower case strings as distinct.459 :param attribute: Filter objects with unique values for this attribute.460 """461 getter = make_attrgetter(462 environment, attribute, postprocess=ignore_case if not case_sensitive else None463 )464 seen = set()465466 for item in value:467 key = getter(item)468469 if key not in seen:470 seen.add(key)471 yield item472473

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 474–476why, one step back
474@async_variant(sync_do_unique) # type: ignore
475async def do_unique(476 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 477why, one step back
477 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 478why, one step back
478 case_sensitive: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 479why, one step back
479 attribute: str | int | None = None,

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 480–485why, one step back
480) -> "t.Iterator[V]":
481 return sync_do_unique(482 environment, await auto_to_list(value), case_sensitive, attribute483 )484485

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 486–490why, one step back
486def _min_or_max(
487 environment: "Environment",488 value: "t.Iterable[V]",489 func: "t.Callable[..., V]",490 case_sensitive: bool,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 491–492why, one step back
491 attribute: str | int | None,
492) -> "V | Undefined":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 493–505why, one step back
493 it = iter(value)
494495 try:496 first = next(it)497 except StopIteration:498 return environment.undefined("No aggregated item, sequence was empty.")499500 key_func = make_attrgetter(501 environment, attribute, postprocess=ignore_case if not case_sensitive else None502 )503 return func(chain([first], it), key=key_func)504505

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 506why, one step back
506@pass_environment

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 507–510why, one step back
507def do_min(
508 environment: "Environment",509 value: "t.Iterable[V]",510 case_sensitive: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 511–512why, one step back
511 attribute: str | int | None = None,
512) -> "V | Undefined":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 513–525why, one step back
513 """Return the smallest item from the sequence.
514515 .. sourcecode:: jinja516517 {{ [1, 2, 3]|min }}518 -> 1519520 :param case_sensitive: Treat upper and lower case strings as distinct.521 :param attribute: Get the object with the min value of this attribute.522 """523 return _min_or_max(environment, value, min, case_sensitive, attribute)524525

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 526why, one step back
526@pass_environment

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 527–530why, one step back
527def do_max(
528 environment: "Environment",529 value: "t.Iterable[V]",530 case_sensitive: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 531–532why, one step back
531 attribute: str | int | None = None,
532) -> "V | Undefined":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 533–545why, one step back
533 """Return the largest item from the sequence.
534535 .. sourcecode:: jinja536537 {{ [1, 2, 3]|max }}538 -> 3539540 :param case_sensitive: Treat upper and lower case strings as distinct.541 :param attribute: Get the object with the max value of this attribute.542 """543 return _min_or_max(environment, value, max, case_sensitive, attribute)544545

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 546why, one step back
546def do_default(

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 547–548why, one step back
547 value: V,
548 default_value: V = "", # type: ignore

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 549why, one step back
549 boolean: bool = False,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 550why, one step back
550) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 551–574why, one step back
551 """If the value is undefined it will return the passed default value,
552 otherwise the value of the variable:553554 .. sourcecode:: jinja555556 {{ my_variable|default('my_variable is not defined') }}557558 This will output the value of ``my_variable`` if the variable was559 defined, otherwise ``'my_variable is not defined'``. If you want560 to use default with variables that evaluate to false you have to561 set the second parameter to `true`:562563 .. sourcecode:: jinja564565 {{ ''|default('the string was empty', true) }}566567 .. versionchanged:: 2.11568 It's now possible to configure the :class:`~jinja2.Environment` with569 :class:`~jinja2.ChainableUndefined` to make the `default` filter work570 on nested elements and attributes that may contain undefined values571 in the chain without getting an :exc:`~jinja2.UndefinedError`.572 """573 if isinstance(value, Undefined) or (boolean and not value):574 return default_value

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 575why, one step back
575

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 576–578why, one step back
576 return value
577578

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 579why, one step back
579@pass_eval_context

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 580why, one step back
580def sync_do_join(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 581why, one step back
581 eval_ctx: "EvalContext",

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

line 582why, one step back
582 value: t.Iterable[t.Any],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 583why, one step back
583 d: str = "",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 584why, one step back
584 attribute: str | int | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 585why, one step back
585) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 586–618why, one step back
586 """Return a string which is the concatenation of the strings in the
587 sequence. The separator between elements is an empty string per588 default, you can define it with the optional parameter:589590 .. sourcecode:: jinja591592 {{ [1, 2, 3]|join('|') }}593 -> 1|2|3594595 {{ [1, 2, 3]|join }}596 -> 123597598 It is also possible to join certain attributes of an object:599600 .. sourcecode:: jinja601602 {{ users|join(', ', attribute='username') }}603604 .. versionadded:: 2.6605 The `attribute` parameter was added.606 """607 if attribute is not None:608 value = map(make_attrgetter(eval_ctx.environment, attribute), value)609610 # no automatic escaping? joining is a lot easier then611 if not eval_ctx.autoescape:612 return str(d).join(map(str, value))613614 # if the delimiter doesn't have an html representation we check615 # if any of the items has. If yes we do a coercion to Markup616 if not hasattr(d, "__html__"):617 value = list(value)618 do_escape = False

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 619why, one step back
619

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 620–624why, one step back
620 for idx, item in enumerate(value):
621 if hasattr(item, "__html__"):622 do_escape = True623 else:624 value[idx] = str(item)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 625why, one step back
625

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 626–629why, one step back
626 if do_escape:
627 d = escape(d)628 else:629 d = str(d)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 630why, one step back
630

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 631–636why, one step back
631 return d.join(value)
632633 # no html involved, to normal joining634 return soft_str(d).join(map(soft_str, value))635636

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 637why, one step back
637@async_variant(sync_do_join) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 638–639why, one step back
638async def do_join(
639 eval_ctx: "EvalContext",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 640why, one step back
640 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 641why, one step back
641 d: str = "",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 642why, one step back
642 attribute: str | int | None = None,

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 643–646why, one step back
643) -> str:
644 return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)645646

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 647why, one step back
647def do_center(value: str, width: int = 80) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 648why, one step back
648 """Centers the value in a field of a given width."""

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 649why, one step back
649 return soft_str(value).center(width)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 650–651why, one step back
650
651

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 652why, one step back
652@pass_environment

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 653why, one step back
653def sync_do_first(environment: "Environment", seq: "t.Iterable[V]") -> "V | Undefined":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 654–660why, one step back
654 """Return the first item of a sequence."""
655 try:656 return next(iter(seq))657 except StopIteration:658 return environment.undefined("No first item, sequence was empty.")659660

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 661why, one step back
661@async_variant(sync_do_first) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 662why, one step back
662async def do_first(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 663–664why, one step back
663 environment: "Environment", seq: "t.AsyncIterable[V] | t.Iterable[V]"
664) -> "V | Undefined":

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 665why, one step back
665 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 666why, one step back
666 return await auto_aiter(seq).__anext__()

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 667–670why, one step back
667 except StopAsyncIteration:
668 return environment.undefined("No first item, sequence was empty.")669670

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 671why, one step back
671@pass_environment

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 672why, one step back
672def do_last(environment: "Environment", seq: "t.Reversible[V]") -> "V | Undefined":

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 673why, one step back
673 """Return the last item of a sequence.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 674–687why, one step back
674
675 Note: Does not work with generators. You may want to explicitly676 convert it to a list:677678 .. sourcecode:: jinja679680 {{ data | selectattr('name', '==', 'Jinja') | list | last }}681 """682 try:683 return next(iter(reversed(seq)))684 except StopIteration:685 return environment.undefined("No last item, sequence was empty.")686687

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 688–690why, one step back
688# No async do_last, it may not be safe in async mode.
689690

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 691why, one step back
691@pass_context

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 692why, one step back
692def do_random(context: "Context", seq: "t.Sequence[V]") -> "V | Undefined":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 693–699why, one step back
693 """Return a random item from the sequence."""
694 try:695 return random.choice(seq)696 except IndexError:697 return context.environment.undefined("No random item, sequence was empty.")698699

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 700why, one step back
700def do_filesizeformat(value: str | float | int, binary: bool = False) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 701–717why, one step back
701 """Format the value like a 'human-readable' file size (i.e. 13 kB,
702 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,703 Giga, etc.), if the second parameter is set to `True` the binary704 prefixes are used (Mebi, Gibi).705 """706 bytes = float(value)707 base = 1024 if binary else 1000708 prefixes = [709 ("KiB" if binary else "kB"),710 ("MiB" if binary else "MB"),711 ("GiB" if binary else "GB"),712 ("TiB" if binary else "TB"),713 ("PiB" if binary else "PB"),714 ("EiB" if binary else "EB"),715 ("ZiB" if binary else "ZB"),716 ("YiB" if binary else "YB"),717 ]

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 718why, one step back
718

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 719–725why, one step back
719 if bytes == 1:
720 return "1 Byte"721 elif bytes < base:722 return f"{int(bytes)} Bytes"723 else:724 for i, prefix in enumerate(prefixes):725 unit = base ** (i + 2)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 726why, one step back
726

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 727–728why, one step back
727 if bytes < unit:
728 return f"{base * bytes / unit:.1f} {prefix}"

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 729why, one step back
729

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 730–732why, one step back
730 return f"{base * bytes / unit:.1f} {prefix}"
731732

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 733why, one step back
733def do_pprint(value: t.Any) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 734why, one step back
734 """Pretty print a variable. Useful for debugging."""

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 735why, one step back
735 return pformat(value)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 736–740why, one step back
736
737738_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")739740

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 741why, one step back
741@pass_eval_context

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 742why, one step back
742def do_urlize(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 743–744why, one step back
743 eval_ctx: "EvalContext",
744 value: str,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 745why, one step back
745 trim_url_limit: int | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 746why, one step back
746 nofollow: bool = False,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 747–749why, one step back
747 target: str | None = None,
748 rel: str | None = None,749 extra_schemes: t.Iterable[str] | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 750why, one step back
750) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 751–820why, one step back
751 """Convert URLs in text into clickable links.
752753 This may not recognize links in some situations. Usually, a more754 comprehensive formatter, such as a Markdown library, is a better755 choice.756757 Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email758 addresses. Links with trailing punctuation (periods, commas, closing759 parentheses) and leading punctuation (opening parentheses) are760 recognized excluding the punctuation. Email addresses that include761 header fields are not recognized (for example,762 ``mailto:address@example.com?cc=copy@example.com``).763764 :param value: Original text containing URLs to link.765 :param trim_url_limit: Shorten displayed URL values to this length.766 :param nofollow: Add the ``rel=nofollow`` attribute to links.767 :param target: Add the ``target`` attribute to links.768 :param rel: Add the ``rel`` attribute to links.769 :param extra_schemes: Recognize URLs that start with these schemes770 in addition to the default behavior. Defaults to771 ``env.policies["urlize.extra_schemes"]``, which defaults to no772 extra schemes.773774 .. versionchanged:: 3.0775 The ``extra_schemes`` parameter was added.776777 .. versionchanged:: 3.0778 Generate ``https://`` links for URLs without a scheme.779780 .. versionchanged:: 3.0781 The parsing rules were updated. Recognize email addresses with782 or without the ``mailto:`` scheme. Validate IP addresses. Ignore783 parentheses and brackets in more cases.784785 .. versionchanged:: 2.8786 The ``target`` parameter was added.787 """788 policies = eval_ctx.environment.policies789 rel_parts = set((rel or "").split())790791 if nofollow:792 rel_parts.add("nofollow")793794 rel_parts.update((policies["urlize.rel"] or "").split())795 rel = " ".join(sorted(rel_parts)) or None796797 if target is None:798 target = policies["urlize.target"]799800 if extra_schemes is None:801 extra_schemes = policies["urlize.extra_schemes"] or ()802803 for scheme in extra_schemes:804 if _uri_scheme_re.fullmatch(scheme) is None:805 raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")806807 rv = urlize(808 value,809 trim_url_limit=trim_url_limit,810 rel=rel,811 target=target,812 extra_schemes=extra_schemes,813 )814815 if eval_ctx.autoescape:816 rv = Markup(rv)817818 return rv819820

Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db

line 821why, one step back
821def do_indent(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 822why, one step back
822 s: str, width: int | str = 4, first: bool = False, blank: bool = False

Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db

line 823why, one step back
823) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 824–826why, one step back
824 """Return a copy of the string with each line indented by 4 spaces. The
825 first line and blank lines are not indented by default.826

Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db

line 827why, one step back
827 :param width: Number of spaces, or a string, to indent by.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 828–830why, one step back
828 :param first: Don't skip indenting the first line.
829 :param blank: Don't skip indenting empty lines.830

Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db

lines 831–833why, one step back
831 .. versionchanged:: 3.0
832 ``width`` can be a string.833

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 834–838why, one step back
834 .. versionchanged:: 2.10
835 Blank lines are not indented by default.836837 Rename the ``indentfirst`` argument to ``first``.838 """

Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db

lines 839–843why, one step back
839 if isinstance(width, str):
840 indention = width841 else:842 indention = " " * width843

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 844–868why, one step back
844 newline = "\n"
845846 if isinstance(s, Markup):847 indention = Markup(indention)848 newline = Markup(newline)849850 s += newline # this quirk is necessary for splitlines method851852 if blank:853 rv = (newline + indention).join(s.splitlines())854 else:855 lines = s.splitlines()856 rv = lines.pop(0)857858 if lines:859 rv += newline + newline.join(860 indention + line if line else line for line in lines861 )862863 if first:864 rv = indention + rv865866 return rv867868

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 869why, one step back
869@pass_environment

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 870–875why, one step back
870def do_truncate(
871 env: "Environment",872 s: str,873 length: int = 255,874 killwords: bool = False,875 end: str = "...",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 876why, one step back
876 leeway: int | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 877why, one step back
877) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 878–902why, one step back
878 """Return a truncated copy of the string. The length is specified
879 with the first parameter which defaults to ``255``. If the second880 parameter is ``true`` the filter will cut the text at length. Otherwise881 it will discard the last word. If the text was in fact882 truncated it will append an ellipsis sign (``"..."``). If you want a883 different ellipsis sign than ``"..."`` you can specify it using the884 third parameter. Strings that only exceed the length by the tolerance885 margin given in the fourth parameter will not be truncated.886887 .. sourcecode:: jinja888889 {{ "foo bar baz qux"|truncate(9) }}890 -> "foo..."891 {{ "foo bar baz qux"|truncate(9, True) }}892 -> "foo ba..."893 {{ "foo bar baz qux"|truncate(11) }}894 -> "foo bar baz qux"895 {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}896 -> "foo bar..."897898 The default leeway on newer Jinja versions is 5 and was 0 before but899 can be reconfigured globally.900 """901 if leeway is None:902 leeway = env.policies["truncate.leeway"]

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 903why, one step back
903

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 904–905why, one step back
904 assert length >= len(end), f"expected length >= {len(end)}, got {length}"
905 assert leeway >= 0, f"expected leeway >= 0, got {leeway}"

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 906why, one step back
906

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 907–908why, one step back
907 if len(s) <= length + leeway:
908 return s

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 909why, one step back
909

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 910–911why, one step back
910 if killwords:
911 return s[: length - len(end)] + end

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 912why, one step back
912

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 913–916why, one step back
913 result = s[: length - len(end)].rsplit(" ", 1)[0]
914 return result + end915916

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 917why, one step back
917@pass_environment

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 918why, one step back
918def do_wordwrap(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 919–922why, one step back
919 environment: "Environment",
920 s: str,921 width: int = 79,922 break_long_words: bool = True,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 923why, one step back
923 wrapstring: str | None = None,

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 924–925why, one step back
924 break_on_hyphens: bool = True,
925) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 926–948why, one step back
926 """Wrap a string to the given width. Existing newlines are treated
927 as paragraphs to be wrapped separately.928929 :param s: Original text to wrap.930 :param width: Maximum length of wrapped lines.931 :param break_long_words: If a word is longer than ``width``, break932 it across lines.933 :param break_on_hyphens: If a word contains hyphens, it may be split934 across lines.935 :param wrapstring: String to join each wrapped line. Defaults to936 :attr:`Environment.newline_sequence`.937938 .. versionchanged:: 2.11939 Existing newlines are treated as paragraphs wrapped separately.940941 .. versionchanged:: 2.11942 Added the ``break_on_hyphens`` parameter.943944 .. versionchanged:: 2.7945 Added the ``wrapstring`` parameter.946 """947 import textwrap948

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 949why, one step back
949 if wrapstring is None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 950–972why, one step back
950 wrapstring = environment.newline_sequence
951952 # textwrap.wrap doesn't consider existing newlines when wrapping.953 # If the string has a newline before width, wrap will still insert954 # a newline at width, resulting in a short line. Instead, split and955 # wrap each paragraph individually.956 return wrapstring.join(957 [958 wrapstring.join(959 textwrap.wrap(960 line,961 width=width,962 expand_tabs=False,963 replace_whitespace=False,964 break_long_words=break_long_words,965 break_on_hyphens=break_on_hyphens,966 )967 )968 for line in s.splitlines()969 ]970 )971972

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 973–976why, one step back
973_word_re = re.compile(r"\w+")
974975976def do_wordcount(s: str) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 977–980why, one step back
977 """Count the words in that string."""
978 return len(_word_re.findall(soft_str(s)))979980

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 981why, one step back
981def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 982–992why, one step back
982 """Convert the value into an integer. If the
983 conversion doesn't work it will return ``0``. You can984 override this default using the first parameter. You985 can also override the default base (10) in the second986 parameter, which handles input with prefixes such as987 0b, 0o and 0x for bases 2, 8 and 16 respectively.988 The base is ignored for decimal numbers and non-string values.989 """990 try:991 if isinstance(value, str):992 return int(value, base)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 993why, one step back
993

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 994–998why, one step back
994 return int(value)
995 except (TypeError, ValueError):996 # this quirk is necessary so that "42.23"|int gives 42.997 try:998 return int(float(value))

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 999why, one step back
999 except (TypeError, ValueError, OverflowError):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1000–1002why, one step back
1000 return default
10011002

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1003why, one step back
1003def do_float(value: t.Any, default: float = 0.0) -> float:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1004–1013why, one step back
1004 """Convert the value into a floating point number. If the
1005 conversion doesn't work it will return ``0.0``. You can1006 override this default using the first parameter.1007 """1008 try:1009 return float(value)1010 except (TypeError, ValueError):1011 return default10121013

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1014why, one step back
1014def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1015–1037why, one step back
1015 """Apply the given values to a `printf-style`_ format string, like
1016 ``string % values``.10171018 .. sourcecode:: jinja10191020 {{ "%s, %s!"|format(greeting, name) }}1021 Hello, World!10221023 In most cases it should be more convenient and efficient to use the1024 ``%`` operator or :meth:`str.format`.10251026 .. code-block:: text10271028 {{ "%s, %s!" % (greeting, name) }}1029 {{ "{}, {}!".format(greeting, name) }}10301031 .. _printf-style: https://docs.python.org/library/stdtypes.html1032 #printf-style-string-formatting1033 """1034 if args and kwargs:1035 raise FilterArgumentError(1036 "can't handle positional and keyword arguments at the same time"1037 )

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1038why, one step back
1038

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1039–1041why, one step back
1039 return soft_str(value) % (kwargs or args)
10401041

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1042why, one step back
1042def do_trim(value: str, chars: str | None = None) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1043–1046why, one step back
1043 """Strip leading and trailing characters, by default whitespace."""
1044 return soft_str(value).strip(chars)10451046

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1047why, one step back
1047def do_striptags(value: "str | HasHTML") -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1048–1049why, one step back
1048 """Strip SGML/XML tags and replace adjacent whitespace by one space."""
1049 if hasattr(value, "__html__"):

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1050–1051why, one step back
1050 value = t.cast("HasHTML", value).__html__()
1051

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1052–1054why, one step back
1052 return Markup(str(value)).striptags()
10531054

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1055why, one step back
1055def sync_do_slice(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1056why, one step back
1056 value: "t.Collection[V]", slices: int, fill_with: "V | None" = None

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1057why, one step back
1057) -> "t.Iterator[list[V]]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1058–1081why, one step back
1058 """Slice an iterator and return a list of lists containing
1059 those items. Useful if you want to create a div containing1060 three ul tags that represent columns:10611062 .. sourcecode:: html+jinja10631064 <div class="columnwrapper">1065 {%- for column in items|slice(3) %}1066 <ul class="column-{{ loop.index }}">1067 {%- for item in column %}1068 <li>{{ item }}</li>1069 {%- endfor %}1070 </ul>1071 {%- endfor %}1072 </div>10731074 If you pass it a second argument it's used to fill missing1075 values on the last iteration.1076 """1077 seq = list(value)1078 length = len(seq)1079 items_per_slice = length // slices1080 slices_with_extra = length % slices1081 offset = 0

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1082why, one step back
1082

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1083–1084why, one step back
1083 for slice_number in range(slices):
1084 start = offset + slice_number * items_per_slice

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1085why, one step back
1085

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1086–1087why, one step back
1086 if slice_number < slices_with_extra:
1087 offset += 1

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1088why, one step back
1088

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1089–1090why, one step back
1089 end = offset + (slice_number + 1) * items_per_slice
1090 tmp = seq[start:end]

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1091why, one step back
1091

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1092–1093why, one step back
1092 if fill_with is not None and slice_number >= slices_with_extra:
1093 tmp.append(fill_with)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1094why, one step back
1094

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1095–1097why, one step back
1095 yield tmp
10961097

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1098why, one step back
1098@async_variant(sync_do_slice) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1099why, one step back
1099async def do_slice(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1100why, one step back
1100 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1101why, one step back
1101 slices: int,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1102why, one step back
1102 fill_with: t.Any | None = None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1103why, one step back
1103) -> "t.Iterator[list[V]]":

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1104–1106why, one step back
1104 return sync_do_slice(await auto_to_list(value), slices, fill_with)
11051106

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1107why, one step back
1107def do_batch(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1108why, one step back
1108 value: "t.Iterable[V]", linecount: int, fill_with: "V | None" = None

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1109why, one step back
1109) -> "t.Iterator[list[V]]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1110–1127why, one step back
1110 """
1111 A filter that batches items. It works pretty much like `slice`1112 just the other way round. It returns a list of lists with the1113 given number of items. If you provide a second parameter this1114 is used to fill up missing items. See this example:11151116 .. sourcecode:: html+jinja11171118 <table>1119 {%- for row in items|batch(3, '&nbsp;') %}1120 <tr>1121 {%- for column in row %}1122 <td>{{ column }}</td>1123 {%- endfor %}1124 </tr>1125 {%- endfor %}1126 </table>1127 """

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1128why, one step back
1128 tmp: list[V] = []

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1129why, one step back
1129

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1130–1133why, one step back
1130 for item in value:
1131 if len(tmp) == linecount:1132 yield tmp1133 tmp = []

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1134why, one step back
1134

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1135why, one step back
1135 tmp.append(item)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1136why, one step back
1136

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1137–1139why, one step back
1137 if tmp:
1138 if fill_with is not None and len(tmp) < linecount:1139 tmp += [fill_with] * (linecount - len(tmp))

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1140why, one step back
1140

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1141–1143why, one step back
1141 yield tmp
11421143

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1144–1148why, one step back
1144def do_round(
1145 value: float,1146 precision: int = 0,1147 method: 'te.Literal["common", "ceil", "floor"]' = "common",1148) -> float:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1149–1175why, one step back
1149 """Round the number to a given precision. The first
1150 parameter specifies the precision (default is ``0``), the1151 second the rounding method:11521153 - ``'common'`` rounds either up or down1154 - ``'ceil'`` always rounds up1155 - ``'floor'`` always rounds down11561157 If you don't specify a method ``'common'`` is used.11581159 .. sourcecode:: jinja11601161 {{ 42.55|round }}1162 -> 43.01163 {{ 42.55|round(1, 'floor') }}1164 -> 42.511651166 Note that even if rounded to 0 precision, a float is returned. If1167 you need a real integer, pipe it through `int`:11681169 .. sourcecode:: jinja11701171 {{ 42.55|round|int }}1172 -> 431173 """1174 if method not in {"common", "ceil", "floor"}:1175 raise FilterArgumentError("method must be common, ceil or floor")

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1176why, one step back
1176

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1177–1178why, one step back
1177 if method == "common":
1178 return round(value, precision)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1179why, one step back
1179

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1180why, one step back
1180 func = getattr(math, method)

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

line 1181why, one step back
1181 return t.cast(float, func(value * (10**precision)) / (10**precision))

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1182–1183why, one step back
1182
1183

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1184–1185why, one step back
1184class _GroupTuple(t.NamedTuple):
1185 grouper: t.Any

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1186why, one step back
1186 list: list[t.Any]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1187why, one step back
1187

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1188–1189why, one step back
1188 # Use the regular tuple repr to hide this subclass if users print
1189 # out the value during debugging.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1190why, one step back
1190 def __repr__(self) -> str:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1191why, one step back
1191 return tuple.__repr__(self)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1192why, one step back
1192

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1193why, one step back
1193 def __str__(self) -> str:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1194–1196why, one step back
1194 return tuple.__str__(self)
11951196

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1197why, one step back
1197@pass_environment

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1198why, one step back
1198def sync_do_groupby(

Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8

lines 1199–1200why, one step back
1199 environment: "Environment",
1200 value: "t.Iterable[V]",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 1201–1202why, one step back
1201 attribute: str | int,
1202 default: t.Any | None = None,

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

line 1203why, one step back
1203 case_sensitive: bool = False,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1204why, one step back
1204) -> "list[_GroupTuple]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1205–1234why, one step back
1205 """Group a sequence of objects by an attribute using Python's
1206 :func:`itertools.groupby`. The attribute can use dot notation for1207 nested access, like ``"address.city"``. Unlike Python's ``groupby``,1208 the values are sorted first so only one group is returned for each1209 unique value.12101211 For example, a list of ``User`` objects with a ``city`` attribute1212 can be rendered in groups. In this example, ``grouper`` refers to1213 the ``city`` value of the group.12141215 .. sourcecode:: html+jinja12161217 <ul>{% for city, items in users|groupby("city") %}1218 <li>{{ city }}1219 <ul>{% for user in items %}1220 <li>{{ user.name }}1221 {% endfor %}</ul>1222 </li>1223 {% endfor %}</ul>12241225 ``groupby`` yields namedtuples of ``(grouper, list)``, which1226 can be used instead of the tuple unpacking above. ``grouper`` is the1227 value of the attribute, and ``list`` is the items with that value.12281229 .. sourcecode:: html+jinja12301231 <ul>{% for group in users|groupby("city") %}1232 <li>{{ group.grouper }}: {{ group.list|join(", ") }}1233 {% endfor %}</ul>1234

Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8

lines 1235–1243why, one step back
1235 You can specify a ``default`` value to use if an object in the list
1236 does not have the given attribute.12371238 .. sourcecode:: jinja12391240 <ul>{% for city, items in users|groupby("city", default="NY") %}1241 <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>1242 {% endfor %}</ul>1243

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1244–1255why, one step back
1244 Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
1245 case-insensitive by default. The ``key`` for each group will have1246 the case of the first item in that group of values. For example, if1247 a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group1248 will have two values. This can be disabled by passing1249 ``case_sensitive=True``.12501251 .. versionchanged:: 3.11252 Added the ``case_sensitive`` parameter. Sorting and grouping is1253 case-insensitive by default, matching other filters that do1254 comparisons.1255

Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8

lines 1256–1258why, one step back
1256 .. versionchanged:: 3.0
1257 Added the ``default`` parameter.1258

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1259–1261why, one step back
1259 .. versionchanged:: 2.6
1260 The attribute supports dot notation for nested access.1261 """

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1262–1268why, one step back
1262 expr = make_attrgetter(
1263 environment,1264 attribute,1265 postprocess=ignore_case if not case_sensitive else None,1266 default=default,1267 )1268 out = [

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1269–1272why, one step back
1269 _GroupTuple(key, list(values))
1270 for key, values in groupby(sorted(value, key=expr), expr)1271 ]1272

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1273–1276why, one step back
1273 if not case_sensitive:
1274 # Return the real key from the first value instead of the lowercase key.1275 output_expr = make_attrgetter(environment, attribute, default=default)1276 out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1277why, one step back
1277

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1278–1280why, one step back
1278 return out
12791280

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1281why, one step back
1281@async_variant(sync_do_groupby) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1282–1283why, one step back
1282async def do_groupby(
1283 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 1284–1286why, one step back
1284 value: "t.AsyncIterable[V] | t.Iterable[V]",
1285 attribute: str | int,1286 default: t.Any | None = None,

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

line 1287why, one step back
1287 case_sensitive: bool = False,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1288why, one step back
1288) -> "list[_GroupTuple]":

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1289–1295why, one step back
1289 expr = make_attrgetter(
1290 environment,1291 attribute,1292 postprocess=ignore_case if not case_sensitive else None,1293 default=default,1294 )1295 out = [

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1296–1298why, one step back
1296 _GroupTuple(key, await auto_to_list(values))
1297 for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)1298 ]

Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40

lines 1299–1305why, one step back
1299
1300 if not case_sensitive:1301 # Return the real key from the first value instead of the lowercase key.1302 output_expr = make_attrgetter(environment, attribute, default=default)1303 out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]13041305 return out

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1306–1307why, one step back
1306
1307

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1308why, one step back
1308@pass_environment

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1309why, one step back
1309def sync_do_sum(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1310–1311why, one step back
1310 environment: "Environment",
1311 iterable: "t.Iterable[V]",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1312why, one step back
1312 attribute: str | int | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 1313–1314why, one step back
1313 start: V = 0, # type: ignore
1314) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1315–1325why, one step back
1315 """Returns the sum of a sequence of numbers plus the value of parameter
1316 'start' (which defaults to 0). When the sequence is empty it returns1317 start.13181319 It is also possible to sum up only certain attributes:13201321 .. sourcecode:: jinja13221323 Total: {{ items|sum(attribute='price') }}13241325 .. versionchanged:: 2.6

Merge branch '3.1.x'David Lordbefore adoption52843b5

lines 1326–1327why, one step back
1326 The ``attribute`` parameter was added to allow summing up over
1327 attributes. Also the ``start`` parameter was moved on to the right.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1328–1330why, one step back
1328 """
1329 if attribute is not None:1330 iterable = map(make_attrgetter(environment, attribute), iterable)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1331why, one step back
1331

Merge branch '3.1.x'David Lordbefore adoption52843b5

line 1332why, one step back
1332 return sum(iterable, start) # type: ignore[no-any-return, call-overload]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1333–1334why, one step back
1333
1334

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1335why, one step back
1335@async_variant(sync_do_sum) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1336–1337why, one step back
1336async def do_sum(
1337 environment: "Environment",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 1338–1339why, one step back
1338 iterable: "t.AsyncIterable[V] | t.Iterable[V]",
1339 attribute: str | int | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 1340–1341why, one step back
1340 start: V = 0, # type: ignore
1341) -> V:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1342–1347why, one step back
1342 rv = start
13431344 if attribute is not None:1345 func = make_attrgetter(environment, attribute)1346 else:1347

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1348why, one step back
1348 def func(x: V) -> V:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1349–1356why, one step back
1349 return x
13501351 async for item in auto_aiter(iterable):1352 rv += func(item)13531354 return rv13551356

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1357why, one step back
1357def sync_do_list(value: "t.Iterable[V]") -> "list[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1358–1363why, one step back
1358 """Convert the value into a list. If it was a string the returned list
1359 will be a list of characters.1360 """1361 return list(value)13621363

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1364why, one step back
1364@async_variant(sync_do_list) # type: ignore

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1365why, one step back
1365async def do_list(value: "t.AsyncIterable[V] | t.Iterable[V]") -> "list[V]":

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1366–1368why, one step back
1366 return await auto_to_list(value)
13671368

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1369why, one step back
1369def do_mark_safe(value: str) -> Markup:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1370–1375why, one step back
1370 """Mark the value as safe which means that in an environment with automatic
1371 escaping enabled this variable will not be escaped.1372 """1373 return Markup(value)13741375

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1376why, one step back
1376def do_mark_unsafe(value: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1377–1380why, one step back
1377 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
1378 return str(value)13791380

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1381why, one step back
1381@typing.overload

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1382why, one step back
1382def do_reverse(value: str) -> str: ...

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1383–1385why, one step back
1383
13841385@typing.overload

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1386why, one step back
1386def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1387–1388why, one step back
1387
1388

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1389why, one step back
1389def do_reverse(value: str | t.Iterable[V]) -> str | t.Iterable[V]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1390–1394why, one step back
1390 """Reverse the object or return an iterator that iterates over it the other
1391 way round.1392 """1393 if isinstance(value, str):1394 return value[::-1]

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1395why, one step back
1395

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1396why, one step back
1396 try:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1397why, one step back
1397 return reversed(value) # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1398–1402why, one step back
1398 except TypeError:
1399 try:1400 rv = list(value)1401 rv.reverse()1402 return rv

Merge branch '3.0.x'David Lordbefore adoptione20a52e

lines 1403–1404why, one step back
1403 except TypeError as e:
1404 raise FilterArgumentError("argument must be iterable") from e

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1405–1406why, one step back
1405
1406

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1407why, one step back
1407@pass_environment

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1408why, one step back
1408def do_attr(environment: "Environment", obj: t.Any, name: str) -> Undefined | t.Any:

Merge branch 'stable'David Lordbefore adoption220e67a

lines 1409–1411why, one step back
1409 """Get an attribute of an object. ``foo|attr("bar")`` works like
1410 ``foo.bar``, but returns undefined instead of falling back to ``foo["bar"]``1411 if the attribute doesn't exist.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1412–1414why, one step back
1412
1413 See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1414 """

Merge branch 'stable'David Lordbefore adoption220e67a

lines 1415–1417why, one step back
1415 # Environment.getattr will fall back to obj[name] if obj.name doesn't exist.
1416 # But we want to call env.getattr to get behavior such as sandboxing.1417 # Determine if the attr exists first, so we know the fallback won't trigger.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1418why, one step back
1418 try:

Merge branch 'stable'David Lordbefore adoption220e67a

lines 1419–1425why, one step back
1419 # This avoids executing properties/descriptors, but misses __getattr__
1420 # and __getattribute__ dynamic attrs.1421 getattr_static(obj, name)1422 except AttributeError:1423 # This finds dynamic attrs, and we know it's not a descriptor at this point.1424 if not hasattr(obj, name):1425 return environment.undefined(obj=obj, name=name)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1426why, one step back
1426

Merge branch 'stable'David Lordbefore adoption220e67a

line 1427why, one step back
1427 return environment.getattr(obj, name)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1428–1429why, one step back
1428
1429

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1430why, one step back
1430@typing.overload

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1431why, one step back
1431def sync_do_map(

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

lines 1432–1436why, one step back
1432 context: "Context",
1433 value: t.Iterable[t.Any],1434 name: str,1435 *args: t.Any,1436 **kwargs: t.Any,

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1437why, one step back
1437) -> t.Iterable[t.Any]: ...

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1438–1440why, one step back
1438
14391440@typing.overload

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1441why, one step back
1441def sync_do_map(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1442why, one step back
1442 context: "Context",

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

line 1443why, one step back
1443 value: t.Iterable[t.Any],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1444–1445why, one step back
1444 *,
1445 attribute: str = ...,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1446why, one step back
1446 default: t.Any | None = None,

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1447why, one step back
1447) -> t.Iterable[t.Any]: ...

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1448–1449why, one step back
1448
1449

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1450why, one step back
1450@pass_context

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1451why, one step back
1451def sync_do_map(

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

lines 1452–1453why, one step back
1452 context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any
1453) -> t.Iterable[t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1454–1484why, one step back
1454 """Applies a filter on a sequence of objects or looks up an attribute.
1455 This is useful when dealing with lists of objects but you are really1456 only interested in a certain value of it.14571458 The basic usage is mapping on an attribute. Imagine you have a list1459 of users but you are only interested in a list of usernames:14601461 .. sourcecode:: jinja14621463 Users on this page: {{ users|map(attribute='username')|join(', ') }}14641465 You can specify a ``default`` value to use if an object in the list1466 does not have the given attribute.14671468 .. sourcecode:: jinja14691470 {{ users|map(attribute="username", default="Anonymous")|join(", ") }}14711472 Alternatively you can let it invoke a filter by passing the name of the1473 filter and the arguments afterwards. A good example would be applying a1474 text conversion filter on a sequence:14751476 .. sourcecode:: jinja14771478 Users on this page: {{ titles|map('lower')|join(', ') }}14791480 Similar to a generator comprehension such as:14811482 .. code-block:: python14831484 (u.username for u in users)

Merge pull request #1364 from Dreamsorcerer/patch-2David Lordbefore adoptioneaf0cca

line 1485why, one step back
1485 (getattr(u, "username", "Anonymous") for u in users)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1486–1492why, one step back
1486 (do_lower(x) for x in titles)
14871488 .. versionchanged:: 2.11.01489 Added the ``default`` parameter.14901491 .. versionadded:: 2.71492 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1493–1496why, one step back
1493 if value:
1494 func = prepare_map(context, args, kwargs)14951496 for item in value:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1497–1499why, one step back
1497 yield func(item)
14981499

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1500–1502why, one step back
1500@typing.overload
1501def do_map(1502 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1503why, one step back
1503 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1504–1506why, one step back
1504 name: str,
1505 *args: t.Any,1506 **kwargs: t.Any,

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1507why, one step back
1507) -> t.Iterable[t.Any]: ...

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1508–1512why, one step back
1508
15091510@typing.overload1511def do_map(1512 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1513why, one step back
1513 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1514–1515why, one step back
1514 *,
1515 attribute: str = ...,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1516why, one step back
1516 default: t.Any | None = None,

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 1517why, one step back
1517) -> t.Iterable[t.Any]: ...

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1518–1519why, one step back
1518
1519

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 1520–1522why, one step back
1520@async_variant(sync_do_map) # type: ignore
1521async def do_map(1522 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1523why, one step back
1523 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 1524–1525why, one step back
1524 *args: t.Any,
1525 **kwargs: t.Any,

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

line 1526why, one step back
1526) -> t.AsyncIterable[t.Any]:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1527–1533why, one step back
1527 if value:
1528 func = prepare_map(context, args, kwargs)15291530 async for item in auto_aiter(value):1531 yield await auto_await(func(item))15321533

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1534why, one step back
1534@pass_context

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1535why, one step back
1535def sync_do_select(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1536–1537why, one step back
1536 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
1537) -> "t.Iterator[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1538–1561why, one step back
1538 """Filters a sequence of objects by applying a test to each object,
1539 and only selecting the objects with the test succeeding.15401541 If no test is specified, each object will be evaluated as a boolean.15421543 Example usage:15441545 .. sourcecode:: jinja15461547 {{ numbers|select("odd") }}1548 {{ numbers|select("odd") }}1549 {{ numbers|select("divisibleby", 3) }}1550 {{ numbers|select("lessthan", 42) }}1551 {{ strings|select("equalto", "mystring") }}15521553 Similar to a generator comprehension such as:15541555 .. code-block:: python15561557 (n for n in numbers if test_odd(n))1558 (n for n in numbers if test_divisibleby(n, 3))15591560 .. versionadded:: 2.71561 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1562why, one step back
1562 return select_or_reject(context, value, args, kwargs, lambda x: x, False)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1563–1564why, one step back
1563
1564

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1565why, one step back
1565@async_variant(sync_do_select) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1566–1567why, one step back
1566async def do_select(
1567 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1568why, one step back
1568 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1569–1574why, one step back
1569 *args: t.Any,
1570 **kwargs: t.Any,1571) -> "t.AsyncIterator[V]":1572 return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)15731574

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1575why, one step back
1575@pass_context

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1576why, one step back
1576def sync_do_reject(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1577–1578why, one step back
1577 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
1578) -> "t.Iterator[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1579–1597why, one step back
1579 """Filters a sequence of objects by applying a test to each object,
1580 and rejecting the objects with the test succeeding.15811582 If no test is specified, each object will be evaluated as a boolean.15831584 Example usage:15851586 .. sourcecode:: jinja15871588 {{ numbers|reject("odd") }}15891590 Similar to a generator comprehension such as:15911592 .. code-block:: python15931594 (n for n in numbers if not test_odd(n))15951596 .. versionadded:: 2.71597 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1598why, one step back
1598 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1599–1600why, one step back
1599
1600

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1601why, one step back
1601@async_variant(sync_do_reject) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1602–1603why, one step back
1602async def do_reject(
1603 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1604why, one step back
1604 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1605–1610why, one step back
1605 *args: t.Any,
1606 **kwargs: t.Any,1607) -> "t.AsyncIterator[V]":1608 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)16091610

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1611why, one step back
1611@pass_context

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1612why, one step back
1612def sync_do_selectattr(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1613–1614why, one step back
1613 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
1614) -> "t.Iterator[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1615–1632why, one step back
1615 """Filters a sequence of objects by applying a test to the specified
1616 attribute of each object, and only selecting the objects with the1617 test succeeding.16181619 If no test is specified, the attribute's value will be evaluated as1620 a boolean.16211622 Example usage:16231624 .. sourcecode:: jinja16251626 {{ users|selectattr("is_active") }}1627 {{ users|selectattr("email", "none") }}16281629 Similar to a generator comprehension such as:16301631 .. code-block:: python1632

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 1633–1634why, one step back
1633 (user for user in users if user.is_active)
1634 (user for user in users if test_none(user.email))

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1635–1637why, one step back
1635
1636 .. versionadded:: 2.71637 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1638why, one step back
1638 return select_or_reject(context, value, args, kwargs, lambda x: x, True)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1639–1640why, one step back
1639
1640

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1641why, one step back
1641@async_variant(sync_do_selectattr) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1642–1643why, one step back
1642async def do_selectattr(
1643 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1644why, one step back
1644 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1645–1650why, one step back
1645 *args: t.Any,
1646 **kwargs: t.Any,1647) -> "t.AsyncIterator[V]":1648 return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)16491650

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1651why, one step back
1651@pass_context

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

line 1652why, one step back
1652def sync_do_rejectattr(

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1653–1654why, one step back
1653 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
1654) -> "t.Iterator[V]":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1655–1670why, one step back
1655 """Filters a sequence of objects by applying a test to the specified
1656 attribute of each object, and rejecting the objects with the test1657 succeeding.16581659 If no test is specified, the attribute's value will be evaluated as1660 a boolean.16611662 .. sourcecode:: jinja16631664 {{ users|rejectattr("is_active") }}1665 {{ users|rejectattr("email", "none") }}16661667 Similar to a generator comprehension such as:16681669 .. code-block:: python1670

Merge branch 'stable'David Lordbefore adoption6aeab5d

lines 1671–1672why, one step back
1671 (user for user in users if not user.is_active)
1672 (user for user in users if not test_none(user.email))

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1673–1675why, one step back
1673
1674 .. versionadded:: 2.71675 """

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1676why, one step back
1676 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1677–1678why, one step back
1677
1678

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1679why, one step back
1679@async_variant(sync_do_rejectattr) # type: ignore

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1680–1681why, one step back
1680async def do_rejectattr(
1681 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1682why, one step back
1682 value: "t.AsyncIterable[V] | t.Iterable[V]",

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1683–1688why, one step back
1683 *args: t.Any,
1684 **kwargs: t.Any,1685) -> "t.AsyncIterator[V]":1686 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)16871688

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 1689why, one step back
1689@pass_eval_context

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1690why, one step back
1690def do_tojson(

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1691why, one step back
1691 eval_ctx: "EvalContext", value: t.Any, indent: int | None = None

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1692why, one step back
1692) -> Markup:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1693–1717why, one step back
1693 """Serialize an object to a string of JSON, and mark it safe to
1694 render in HTML. This filter is only for use in HTML documents.16951696 The returned string is safe to render in HTML documents and1697 ``<script>`` tags. The exception is in HTML attributes that are1698 double quoted; either use single quotes or the ``|forceescape``1699 filter.17001701 :param value: The object to serialize to JSON.1702 :param indent: The ``indent`` parameter passed to ``dumps``, for1703 pretty-printing the value.17041705 .. versionadded:: 2.91706 """1707 policies = eval_ctx.environment.policies1708 dumps = policies["json.dumps_function"]1709 kwargs = policies["json.dumps_kwargs"]17101711 if indent is not None:1712 kwargs = kwargs.copy()1713 kwargs["indent"] = indent17141715 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)17161717

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1718why, one step back
1718def prepare_map(

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 1719why, one step back
1719 context: "Context", args: tuple[t.Any, ...], kwargs: dict[str, t.Any]

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1720–1721why, one step back
1720) -> t.Callable[[t.Any], t.Any]:
1721 if not args and "attribute" in kwargs:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1722–1723why, one step back
1722 attribute = kwargs.pop("attribute")
1723 default = kwargs.pop("default", None)

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1724why, one step back
1724

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1725–1728why, one step back
1725 if kwargs:
1726 raise FilterArgumentError(1727 f"Unexpected keyword argument {next(iter(kwargs))!r}"1728 )

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1729why, one step back
1729

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1730–1732why, one step back
1730 func = make_attrgetter(context.environment, attribute, default=default)
1731 else:1732 try:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1733–1734why, one step back
1733 name = args[0]
1734 args = args[1:]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1735why, one step back
1735 except LookupError:

Merge branch '3.0.x'David Lordbefore adoptione20a52e

line 1736why, one step back
1736 raise FilterArgumentError("map requires a filter argument") from None

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1737why, one step back
1737

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1738why, one step back
1738 def func(item: t.Any) -> t.Any:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1739–1742why, one step back
1739 return context.environment.call_filter(
1740 name, item, args, kwargs, context=context1741 )1742

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1743why, one step back
1743 return func

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1744–1745why, one step back
1744
1745

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1746–1747why, one step back
1746def prepare_select_or_reject(
1747 context: "Context",

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

lines 1748–1749why, one step back
1748 args: tuple[t.Any, ...],
1749 kwargs: dict[str, t.Any],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1750–1752why, one step back
1750 modfunc: t.Callable[[t.Any], t.Any],
1751 lookup_attr: bool,1752) -> t.Callable[[t.Any], t.Any]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1753–1754why, one step back
1753 if lookup_attr:
1754 try:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1755why, one step back
1755 attr = args[0]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1756why, one step back
1756 except LookupError:

Merge branch '3.0.x'David Lordbefore adoptione20a52e

line 1757why, one step back
1757 raise FilterArgumentError("Missing parameter for attribute name") from None

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1758why, one step back
1758

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1759–1763why, one step back
1759 transfunc = make_attrgetter(context.environment, attr)
1760 off = 11761 else:1762 off = 01763

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1764why, one step back
1764 def transfunc(x: V) -> V:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1765–1767why, one step back
1765 return x
17661767 try:

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1768–1769why, one step back
1768 name = args[off]
1769 args = args[1 + off :]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1770why, one step back
1770

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1771why, one step back
1771 def func(item: t.Any) -> t.Any:

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 1772why, one step back
1772 return context.environment.call_test(name, item, args, kwargs, context)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1773–1774why, one step back
1773
1774 except LookupError:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 1775why, one step back
1775 func = bool # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 1776why, one step back
1776

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

line 1777why, one step back
1777 return lambda item: modfunc(func(transfunc(item)))

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1778–1779why, one step back
1778
1779

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1780–1782why, one step back
1780def select_or_reject(
1781 context: "Context",1782 value: "t.Iterable[V]",

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

lines 1783–1784why, one step back
1783 args: tuple[t.Any, ...],
1784 kwargs: dict[str, t.Any],

Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919

lines 1785–1791why, one step back
1785 modfunc: t.Callable[[t.Any], t.Any],
1786 lookup_attr: bool,1787) -> "t.Iterator[V]":1788 if value:1789 func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)17901791 for item in value:

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1792–1797why, one step back
1792 if func(item):
1793 yield item179417951796async def async_select_or_reject(1797 context: "Context",

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 1798why, one step back
1798 value: "t.AsyncIterable[V] | t.Iterable[V]",

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

lines 1799–1800why, one step back
1799 args: tuple[t.Any, ...],
1800 kwargs: dict[str, t.Any],

Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b

lines 1801–1807why, one step back
1801 modfunc: t.Callable[[t.Any], t.Any],
1802 lookup_attr: bool,1803) -> "t.AsyncIterator[V]":1804 if value:1805 func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)18061807 async for item in auto_aiter(value):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1808–1836why, one step back
1808 if func(item):
1809 yield item181018111812FILTERS = {1813 "abs": abs,1814 "attr": do_attr,1815 "batch": do_batch,1816 "capitalize": do_capitalize,1817 "center": do_center,1818 "count": len,1819 "d": do_default,1820 "default": do_default,1821 "dictsort": do_dictsort,1822 "e": escape,1823 "escape": escape,1824 "filesizeformat": do_filesizeformat,1825 "first": do_first,1826 "float": do_float,1827 "forceescape": do_forceescape,1828 "format": do_format,1829 "groupby": do_groupby,1830 "indent": do_indent,1831 "int": do_int,1832 "join": do_join,1833 "last": do_last,1834 "length": len,1835 "list": do_list,1836 "lower": do_lower,

Merge pull request #1564 from pallets/feature/pairsDavid Lordbefore adoptiona819eb3

line 1837why, one step back
1837 "items": do_items,

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1838–1867why, one step back
1838 "map": do_map,
1839 "min": do_min,1840 "max": do_max,1841 "pprint": do_pprint,1842 "random": do_random,1843 "reject": do_reject,1844 "rejectattr": do_rejectattr,1845 "replace": do_replace,1846 "reverse": do_reverse,1847 "round": do_round,1848 "safe": do_mark_safe,1849 "select": do_select,1850 "selectattr": do_selectattr,1851 "slice": do_slice,1852 "sort": do_sort,1853 "string": soft_str,1854 "striptags": do_striptags,1855 "sum": do_sum,1856 "title": do_title,1857 "trim": do_trim,1858 "truncate": do_truncate,1859 "unique": do_unique,1860 "upper": do_upper,1861 "urlencode": do_urlencode,1862 "urlize": do_urlize,1863 "wordcount": do_wordcount,1864 "wordwrap": do_wordwrap,1865 "xmlattr": do_xmlattr,1866 "tojson": do_tojson,1867}