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 fileTake 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 back1"""Built-in template filters used with the ``|`` operator."""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 2why, one step back2update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 3–5why, one step back3import math4import random5import reMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 6–7why, one step back6import typing7import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 8why, one step back8from collections import abcMerge branch 'stable'David Lordbefore adoption220e67a
line 9why, one step back9from inspect import getattr_staticupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 10–16why, one step back10from itertools import chain11from itertools import groupby1213from markupsafe import escape14from markupsafe import Markup15from markupsafe import soft_str16Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 17–20why, one step back17from .async_utils import async_variant18from .async_utils import auto_aiter19from .async_utils import auto_await20from .async_utils import auto_to_listupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 21–23why, one step back21from .exceptions import FilterArgumentError22from .runtime import Undefined23from .utils import htmlsafe_json_dumpsMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 24–26why, one step back24from .utils import pass_context25from .utils import pass_environment26from .utils import pass_eval_contextupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 27–30why, one step back27from .utils import pformat28from .utils import url_quote29from .utils import urlize30Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 31–32why, one step back31if t.TYPE_CHECKING:32 import typing_extensions as teMerge branch '3.1.x'David Lordbefore adoptionde61312
line 33why, one step back33Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 34–37why, one step back34 from .environment import Environment35 from .nodes import EvalContext36 from .runtime import Context37 from .sandbox import SandboxedEnvironment # noqa: F401update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 38why, one step back38Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 39–43why, one step back39 class HasHTML(te.Protocol):40 def __html__(self) -> str:41 pass4243Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 44–46why, one step back44F = 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 back4748Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 49why, one step back49def ignore_case(value: V) -> V:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 50–51why, one step back50 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings51 to lowercase and returns other types as-is."""Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 52why, one step back52 if isinstance(value, str):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 53why, one step back53 return t.cast(V, value.lower())update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 54why, one step back54Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 55why, one step back55 return valueupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 56why, one step back56Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 57–59why, one step back5758def make_attrgetter(59 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 60–62why, one step back60 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 back63) -> t.Callable[[t.Any], t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 64–68why, one step back64 """Returns a callable that looks up the given attribute from a65 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 back69 parts = _prepare_attribute_parts(attribute)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 70why, one step back70Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 71–72why, one step back71 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 back73 item = environment.getitem(item, part)74Merge pull request #1356 from BALaka-18/map-filter-defaultDavid Lordbefore adoption8ab9db2
line 75why, one step back75 if default is not None and isinstance(item, Undefined):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 76–85why, one step back76 item = default7778 if postprocess is not None:79 item = postprocess(item)8081 return item8283 return attrgetter8485Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 86–87why, one step back86def make_multi_attrgetter(87 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 88–89why, one step back88 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 back90) -> t.Callable[[t.Any], list[t.Any]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 91–100why, one step back91 """Returns a callable that looks up the given comma separated92 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 back101 if isinstance(attribute, str):drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 102why, one step back102 split: t.Sequence[str | int | None] = attribute.split(",")Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 103–104why, one step back103 else:104 split = [attribute]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 105why, one step back105Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 106–107why, one step back106 parts = [_prepare_attribute_parts(item) for item in split]107Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 108why, one step back108 def attrgetter(item: t.Any) -> list[t.Any]:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 109–111why, one step back109 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 back112 item_i = itemMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 113why, one step back113update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 114–120why, one step back114 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_iMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 121why, one step back121update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 122–126why, one step back122 return items123124 return attrgetter125126Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 127why, one step back127def _prepare_attribute_parts(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 128–129why, one step back128 attr: str | int | None,129) -> list[str | int]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 130–131why, one step back130 if attr is None:131 return []Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 132–133why, one step back132133 if isinstance(attr, str):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 134–135why, one step back134 return [int(x) if x.isdigit() else x for x in attr.split(".")]135Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 136why, one step back136 return [attr]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 137why, one step back137Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 138why, one step back138drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 139why, one step back139def do_forceescape(value: "str | HasHTML") -> Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 140–141why, one step back140 """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 back142 value = t.cast("HasHTML", value).__html__()143update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 144–146why, one step back144 return escape(str(value))145146Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 147why, one step back147def do_urlencode(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 148why, one step back148 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 back149) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 150–168why, one step back150 """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 back169 items: t.Iterable[tuple[str, t.Any]] = value.items()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 170why, one step back170 else:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 171why, one step back171 items = value # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 172–177why, one step back172173 return "&".join(174 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items175 )176177Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 178why, one step back178@pass_eval_contextMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 179why, one step back179def do_replace(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 180why, one step back180 eval_ctx: "EvalContext", s: str, old: str, new: str, count: int | None = NoneMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 181why, one step back181) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 182–197why, one step back182 """Return a copy of the value with all occurrences of a substring183 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 = -1Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 198why, one step back198update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 199–200why, one step back199 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 back201update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 202–209why, one step back202 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 back210update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 211–213why, one step back211 return s.replace(soft_str(old), soft_str(new), count)212213Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 214why, one step back214def do_upper(s: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 215–218why, one step back215 """Convert a value to uppercase."""216 return soft_str(s).upper()217218Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 219why, one step back219def do_lower(s: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 220–223why, one step back220 """Convert a value to lowercase."""221 return soft_str(s).lower()222223drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 224why, one step back224def 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 back225 """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()252253Merge branch '3.1.x'David Lordbefore adoption11550f9
lines 254–256why, one step back254# 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 back257258Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 259why, one step back259@pass_eval_contextMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 260–262why, one step back260def 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 back263 """Create an SGML/XML attribute string based on the items in a dict.264Merge branch '3.1.x'David Lordbefore adoption11550f9
lines 265–266why, one step back265 **Values** that are neither ``none`` nor ``undefined`` are automatically266 escaped, safely allowing untrusted user input.Merge branch '3.1.x'David Lordbefore adoption3fd91e4
line 267why, one step back267Merge branch '3.1.x'David Lordbefore adoption11550f9
lines 268–273why, one step back268 User input should not be used as **keys** to this filter. If any key269 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.273update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 274–290why, one step back274 .. sourcecode:: html+jinja275276 <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 back291Merge branch '3.1.x'David Lordbefore adoption11550f9
lines 292–295why, one step back292 .. versionchanged:: 3.1.4293 Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign294 are not allowed.295Merge branch '3.1.x'David Lordbefore adoption3fd91e4
lines 296–297why, one step back296 .. versionchanged:: 3.1.3297 Keys with spaces are not allowed.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 298why, one step back298 """Merge branch '3.1.x'David Lordbefore adoption3fd91e4
lines 299–304why, one step back299 items = []300301 for key, value in d.items():302 if value is None or isinstance(value, Undefined):303 continue304Merge branch '3.1.x'David Lordbefore adoption11550f9
lines 305–306why, one step back305 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 back307308 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 back311update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 312–313why, one step back312 if autospace and rv:313 rv = " " + rvMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 314–315why, one step back314315 if eval_ctx.autoescape:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 316why, one step back316 rv = Markup(rv)Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 317why, one step back317update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 318–320why, one step back318 return rv319320Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 321why, one step back321def do_capitalize(s: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 322–327why, one step back322 """Capitalize a value. The first character will be uppercase, all others323 lowercase.324 """325 return soft_str(s).capitalize()326327Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 328–331why, one step back328_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 back332 """Return a titlecased version of the value. I.e. words will start with333 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 )342343Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 344why, one step back344def do_dictsort(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 345why, one step back345 value: t.Mapping[K, V],Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 346–348why, one step back346 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 back349) -> list[tuple[K, V]]:Merge pull request #1236 from sixtyfathoms/fix/issue-1184David Lordbefore adoptione45eabc
lines 350–351why, one step back350 """Sort a dict and yield (key, value) pairs. Python dicts may not351 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 back352353 .. 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"')373Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 374why, one step back374 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 back375 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)383384Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 385why, one step back385@pass_environmentMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 386–390why, one step back386def 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 back391 attribute: str | int | None = None,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 392why, one step back392) -> "list[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 393–423why, one step back393 """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:: jinja423Merge branch '3.0.x'David Lordbefore adoption896a621
line 424why, one step back424 {% for user in users|sort(attribute="age,name") %}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 425–440why, one step back425 ...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)439440Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 441why, one step back441@pass_environmentMerge branch 'stable'David Lordbefore adoption6aeab5d
line 442why, one step back442def sync_do_unique(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 443–445why, one step back443 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 back446 attribute: str | int | None = None,Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 447why, one step back447) -> "t.Iterator[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 448–473why, one step back448 """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 item472473Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 474–476why, one step back474@async_variant(sync_do_unique) # type: ignore475async def do_unique(476 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 477why, one step back477 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge branch 'stable'David Lordbefore adoption6aeab5d
line 478why, one step back478 case_sensitive: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 479why, one step back479 attribute: str | int | None = None,Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 480–485why, one step back480) -> "t.Iterator[V]":481 return sync_do_unique(482 environment, await auto_to_list(value), case_sensitive, attribute483 )484485Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 486–490why, one step back486def _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 back491 attribute: str | int | None,492) -> "V | Undefined":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 493–505why, one step back493 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)504505Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 506why, one step back506@pass_environmentMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 507–510why, one step back507def 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 back511 attribute: str | int | None = None,512) -> "V | Undefined":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 513–525why, one step back513 """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)524525Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 526why, one step back526@pass_environmentMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 527–530why, one step back527def 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 back531 attribute: str | int | None = None,532) -> "V | Undefined":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 533–545why, one step back533 """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)544545Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 546why, one step back546def do_default(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 547–548why, one step back547 value: V,548 default_value: V = "", # type: ignoreMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 549why, one step back549 boolean: bool = False,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 550why, one step back550) -> V:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 551–574why, one step back551 """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_valueMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 575why, one step back575update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 576–578why, one step back576 return value577578Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 579why, one step back579@pass_eval_contextMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 580why, one step back580def sync_do_join(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 581why, one step back581 eval_ctx: "EvalContext",switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
line 582why, one step back582 value: t.Iterable[t.Any],Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 583why, one step back583 d: str = "",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 584why, one step back584 attribute: str | int | None = None,Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 585why, one step back585) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 586–618why, one step back586 """Return a string which is the concatenation of the strings in the587 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 = FalseMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 619why, one step back619update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 620–624why, one step back620 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 back625update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 626–629why, one step back626 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 back630update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 631–636why, one step back631 return d.join(value)632633 # no html involved, to normal joining634 return soft_str(d).join(map(soft_str, value))635636Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 637why, one step back637@async_variant(sync_do_join) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 638–639why, one step back638async def do_join(639 eval_ctx: "EvalContext",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 640why, one step back640 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 641why, one step back641 d: str = "",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 642why, one step back642 attribute: str | int | None = None,Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 643–646why, one step back643) -> str:644 return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)645646Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 647why, one step back647def do_center(value: str, width: int = 80) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 648why, one step back648 """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 back649 return soft_str(value).center(width)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 650–651why, one step back650651Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 652why, one step back652@pass_environmentdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 653why, one step back653def 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 back654 """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.")659660Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 661why, one step back661@async_variant(sync_do_first) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 662why, one step back662async def do_first(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 663–664why, one step back663 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 back665 try:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 666why, one step back666 return await auto_aiter(seq).__anext__()Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 667–670why, one step back667 except StopAsyncIteration:668 return environment.undefined("No first item, sequence was empty.")669670Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 671why, one step back671@pass_environmentdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 672why, one step back672def 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 back673 """Return the last item of a sequence.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 674–687why, one step back674675 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.")686687Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 688–690why, one step back688# No async do_last, it may not be safe in async mode.689690Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 691why, one step back691@pass_contextdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 692why, one step back692def 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 back693 """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.")698699drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 700why, one step back700def 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 back701 """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 back718update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 719–725why, one step back719 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 back726update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 727–728why, one step back727 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 back729update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 730–732why, one step back730 return f"{base * bytes / unit:.1f} {prefix}"731732Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 733why, one step back733def do_pprint(value: t.Any) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 734why, one step back734 """Pretty print a variable. Useful for debugging."""Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 735why, one step back735 return pformat(value)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 736–740why, one step back736737738_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")739740Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 741why, one step back741@pass_eval_contextupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 742why, one step back742def do_urlize(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 743–744why, one step back743 eval_ctx: "EvalContext",744 value: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 745why, one step back745 trim_url_limit: int | None = None,Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 746why, one step back746 nofollow: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 747–749why, one step back747 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 back750) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 751–820why, one step back751 """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 rv819820Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db
line 821why, one step back821def do_indent(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 822why, one step back822 s: str, width: int | str = 4, first: bool = False, blank: bool = FalseMerge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db
line 823why, one step back823) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 824–826why, one step back824 """Return a copy of the string with each line indented by 4 spaces. The825 first line and blank lines are not indented by default.826Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db
line 827why, one step back827 :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 back828 :param first: Don't skip indenting the first line.829 :param blank: Don't skip indenting empty lines.830Merge pull request #1167 from LarsKollstedt/allow_indent_with_generic_charDavid Lordbefore adoption1b874db
lines 831–833why, one step back831 .. versionchanged:: 3.0832 ``width`` can be a string.833update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 834–838why, one step back834 .. versionchanged:: 2.10835 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 back839 if isinstance(width, str):840 indention = width841 else:842 indention = " " * width843update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 844–868why, one step back844 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 rv867868Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 869why, one step back869@pass_environmentMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 870–875why, one step back870def 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 back876 leeway: int | None = None,Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 877why, one step back877) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 878–902why, one step back878 """Return a truncated copy of the string. The length is specified879 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 back903update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 904–905why, one step back904 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 back906update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 907–908why, one step back907 if len(s) <= length + leeway:908 return sMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 909why, one step back909update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 910–911why, one step back910 if killwords:911 return s[: length - len(end)] + endMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 912why, one step back912update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 913–916why, one step back913 result = s[: length - len(end)].rsplit(" ", 1)[0]914 return result + end915916Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 917why, one step back917@pass_environmentupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 918why, one step back918def do_wordwrap(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 919–922why, one step back919 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 back923 wrapstring: str | None = None,Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 924–925why, one step back924 break_on_hyphens: bool = True,925) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 926–948why, one step back926 """Wrap a string to the given width. Existing newlines are treated927 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 textwrap948Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 949why, one step back949 if wrapstring is None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 950–972why, one step back950 wrapstring = environment.newline_sequence951952 # 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 )971972Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 973–976why, one step back973_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 back977 """Count the words in that string."""978 return len(_word_re.findall(soft_str(s)))979980Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 981why, one step back981def 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 back982 """Convert the value into an integer. If the983 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 back993update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 994–998why, one step back994 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 back999 except (TypeError, ValueError, OverflowError):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1000–1002why, one step back1000 return default10011002Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1003why, one step back1003def 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 back1004 """Convert the value into a floating point number. If the1005 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 default10121013Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1014why, one step back1014def 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 back1015 """Apply the given values to a `printf-style`_ format string, like1016 ``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 back1038update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1039–1041why, one step back1039 return soft_str(value) % (kwargs or args)10401041drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1042why, one step back1042def do_trim(value: str, chars: str | None = None) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1043–1046why, one step back1043 """Strip leading and trailing characters, by default whitespace."""1044 return soft_str(value).strip(chars)10451046drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1047why, one step back1047def do_striptags(value: "str | HasHTML") -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1048–1049why, one step back1048 """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 back1050 value = t.cast("HasHTML", value).__html__()1051update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1052–1054why, one step back1052 return Markup(str(value)).striptags()10531054Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1055why, one step back1055def sync_do_slice(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1056why, one step back1056 value: "t.Collection[V]", slices: int, fill_with: "V | None" = NoneUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1057why, one step back1057) -> "t.Iterator[list[V]]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1058–1081why, one step back1058 """Slice an iterator and return a list of lists containing1059 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 = 0Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1082why, one step back1082update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1083–1084why, one step back1083 for slice_number in range(slices):1084 start = offset + slice_number * items_per_sliceMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1085why, one step back1085update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1086–1087why, one step back1086 if slice_number < slices_with_extra:1087 offset += 1Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1088why, one step back1088update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1089–1090why, one step back1089 end = offset + (slice_number + 1) * items_per_slice1090 tmp = seq[start:end]Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1091why, one step back1091update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1092–1093why, one step back1092 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 back1094update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1095–1097why, one step back1095 yield tmp10961097Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1098why, one step back1098@async_variant(sync_do_slice) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1099why, one step back1099async def do_slice(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1100why, one step back1100 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1101why, one step back1101 slices: int,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1102why, one step back1102 fill_with: t.Any | None = None,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1103why, one step back1103) -> "t.Iterator[list[V]]":Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1104–1106why, one step back1104 return sync_do_slice(await auto_to_list(value), slices, fill_with)11051106Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1107why, one step back1107def do_batch(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1108why, one step back1108 value: "t.Iterable[V]", linecount: int, fill_with: "V | None" = NoneUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1109why, one step back1109) -> "t.Iterator[list[V]]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1110–1127why, one step back1110 """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, ' ') %}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 back1128 tmp: list[V] = []Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1129why, one step back1129update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1130–1133why, one step back1130 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 back1134update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1135why, one step back1135 tmp.append(item)Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1136why, one step back1136update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1137–1139why, one step back1137 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 back1140update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1141–1143why, one step back1141 yield tmp11421143Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1144–1148why, one step back1144def 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 back1149 """Round the number to a given precision. The first1150 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 back1176update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1177–1178why, one step back1177 if method == "common":1178 return round(value, precision)Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1179why, one step back1179update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1180why, one step back1180 func = getattr(math, method)Merge branch '3.0.x'David Lordbefore adoption80e6c4b
line 1181why, one step back1181 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 back11821183Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1184–1185why, one step back1184class _GroupTuple(t.NamedTuple):1185 grouper: t.AnyUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1186why, one step back1186 list: list[t.Any]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1187why, one step back1187Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1188–1189why, one step back1188 # Use the regular tuple repr to hide this subclass if users print1189 # out the value during debugging.Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1190why, one step back1190 def __repr__(self) -> str:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1191why, one step back1191 return tuple.__repr__(self)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1192why, one step back1192Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1193why, one step back1193 def __str__(self) -> str:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1194–1196why, one step back1194 return tuple.__str__(self)11951196Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1197why, one step back1197@pass_environmentMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1198why, one step back1198def sync_do_groupby(Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8
lines 1199–1200why, one step back1199 environment: "Environment",1200 value: "t.Iterable[V]",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1201–1202why, one step back1201 attribute: str | int,1202 default: t.Any | None = None,Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40
line 1203why, one step back1203 case_sensitive: bool = False,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1204why, one step back1204) -> "list[_GroupTuple]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1205–1234why, one step back1205 """Group a sequence of objects by an attribute using Python's1206 :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>1234Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8
lines 1235–1243why, one step back1235 You can specify a ``default`` value to use if an object in the list1236 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>1243Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40
lines 1244–1255why, one step back1244 Like the :func:`~jinja-filters.sort` filter, sorting and grouping is1245 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.1255Merge pull request #1360 from lisongmin/add-default-value-to-groupbyDavid Lordbefore adoptionc752dc8
lines 1256–1258why, one step back1256 .. versionchanged:: 3.01257 Added the ``default`` parameter.1258update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1259–1261why, one step back1259 .. versionchanged:: 2.61260 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 back1262 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 back1269 _GroupTuple(key, list(values))1270 for key, values in groupby(sorted(value, key=expr), expr)1271 ]1272Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40
lines 1273–1276why, one step back1273 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 back1277Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40
lines 1278–1280why, one step back1278 return out12791280Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1281why, one step back1281@async_variant(sync_do_groupby) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1282–1283why, one step back1282async def do_groupby(1283 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1284–1286why, one step back1284 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 back1287 case_sensitive: bool = False,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1288why, one step back1288) -> "list[_GroupTuple]":Merge pull request #1465 from wombatonfire/groupby-case-sensitiveDavid Lordbefore adoptiona12ad40
lines 1289–1295why, one step back1289 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 back1296 _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 back12991300 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 outMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1306–1307why, one step back13061307Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1308why, one step back1308@pass_environmentMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1309why, one step back1309def sync_do_sum(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1310–1311why, one step back1310 environment: "Environment",1311 iterable: "t.Iterable[V]",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1312why, one step back1312 attribute: str | int | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1313–1314why, one step back1313 start: V = 0, # type: ignore1314) -> V:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1315–1325why, one step back1315 """Returns the sum of a sequence of numbers plus the value of parameter1316 '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.6Merge branch '3.1.x'David Lordbefore adoption52843b5
lines 1326–1327why, one step back1326 The ``attribute`` parameter was added to allow summing up over1327 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 back1328 """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 back1331Merge branch '3.1.x'David Lordbefore adoption52843b5
line 1332why, one step back1332 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 back13331334Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1335why, one step back1335@async_variant(sync_do_sum) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1336–1337why, one step back1336async def do_sum(1337 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1338–1339why, one step back1338 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 back1340 start: V = 0, # type: ignore1341) -> V:Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1342–1347why, one step back1342 rv = start13431344 if attribute is not None:1345 func = make_attrgetter(environment, attribute)1346 else:1347Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1348why, one step back1348 def func(x: V) -> V:Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1349–1356why, one step back1349 return x13501351 async for item in auto_aiter(iterable):1352 rv += func(item)13531354 return rv13551356Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1357why, one step back1357def sync_do_list(value: "t.Iterable[V]") -> "list[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1358–1363why, one step back1358 """Convert the value into a list. If it was a string the returned list1359 will be a list of characters.1360 """1361 return list(value)13621363Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1364why, one step back1364@async_variant(sync_do_list) # type: ignoredrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1365why, one step back1365async 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 back1366 return await auto_to_list(value)13671368Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1369why, one step back1369def do_mark_safe(value: str) -> Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1370–1375why, one step back1370 """Mark the value as safe which means that in an environment with automatic1371 escaping enabled this variable will not be escaped.1372 """1373 return Markup(value)13741375Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1376why, one step back1376def do_mark_unsafe(value: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1377–1380why, one step back1377 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1378 return str(value)13791380Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1381why, one step back1381@typing.overloadMerge branch '3.1.x'David Lordbefore adoptionde61312
line 1382why, one step back1382def do_reverse(value: str) -> str: ...Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1383–1385why, one step back138313841385@typing.overloadMerge branch '3.1.x'David Lordbefore adoptionde61312
line 1386why, one step back1386def 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 back13871388drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1389why, one step back1389def 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 back1390 """Reverse the object or return an iterator that iterates over it the other1391 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 back1395update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1396why, one step back1396 try:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1397why, one step back1397 return reversed(value) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1398–1402why, one step back1398 except TypeError:1399 try:1400 rv = list(value)1401 rv.reverse()1402 return rvMerge branch '3.0.x'David Lordbefore adoptione20a52e
lines 1403–1404why, one step back1403 except TypeError as e:1404 raise FilterArgumentError("argument must be iterable") from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1405–1406why, one step back14051406Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1407why, one step back1407@pass_environmentdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1408why, one step back1408def do_attr(environment: "Environment", obj: t.Any, name: str) -> Undefined | t.Any:Merge branch 'stable'David Lordbefore adoption220e67a
lines 1409–1411why, one step back1409 """Get an attribute of an object. ``foo|attr("bar")`` works like1410 ``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 back14121413 See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1414 """Merge branch 'stable'David Lordbefore adoption220e67a
lines 1415–1417why, one step back1415 # 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 back1418 try:Merge branch 'stable'David Lordbefore adoption220e67a
lines 1419–1425why, one step back1419 # 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 back1426Merge branch 'stable'David Lordbefore adoption220e67a
line 1427why, one step back1427 return environment.getattr(obj, name)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1428–1429why, one step back14281429Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1430why, one step back1430@typing.overloadMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1431why, one step back1431def sync_do_map(switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
lines 1432–1436why, one step back1432 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 back1437) -> t.Iterable[t.Any]: ...Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1438–1440why, one step back143814391440@typing.overloadMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1441why, one step back1441def sync_do_map(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1442why, one step back1442 context: "Context",switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
line 1443why, one step back1443 value: t.Iterable[t.Any],Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1444–1445why, one step back1444 *,1445 attribute: str = ...,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1446why, one step back1446 default: t.Any | None = None,Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1447why, one step back1447) -> t.Iterable[t.Any]: ...Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1448–1449why, one step back14481449Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1450why, one step back1450@pass_contextMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1451why, one step back1451def sync_do_map(switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
lines 1452–1453why, one step back1452 context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any1453) -> t.Iterable[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1454–1484why, one step back1454 """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 back1485 (getattr(u, "username", "Anonymous") for u in users)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1486–1492why, one step back1486 (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 back1493 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 back1497 yield func(item)14981499Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1500–1502why, one step back1500@typing.overload1501def do_map(1502 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1503why, one step back1503 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1504–1506why, one step back1504 name: str,1505 *args: t.Any,1506 **kwargs: t.Any,Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1507why, one step back1507) -> t.Iterable[t.Any]: ...Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1508–1512why, one step back150815091510@typing.overload1511def do_map(1512 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1513why, one step back1513 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1514–1515why, one step back1514 *,1515 attribute: str = ...,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1516why, one step back1516 default: t.Any | None = None,Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1517why, one step back1517) -> t.Iterable[t.Any]: ...Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1518–1519why, one step back15181519Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1520–1522why, one step back1520@async_variant(sync_do_map) # type: ignore1521async def do_map(1522 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1523why, one step back1523 value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1524–1525why, one step back1524 *args: t.Any,1525 **kwargs: t.Any,switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
line 1526why, one step back1526) -> t.AsyncIterable[t.Any]:Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1527–1533why, one step back1527 if value:1528 func = prepare_map(context, args, kwargs)15291530 async for item in auto_aiter(value):1531 yield await auto_await(func(item))15321533Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1534why, one step back1534@pass_contextMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1535why, one step back1535def sync_do_select(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1536–1537why, one step back1536 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1537) -> "t.Iterator[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1538–1561why, one step back1538 """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 back1562 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 back15631564Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1565why, one step back1565@async_variant(sync_do_select) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1566–1567why, one step back1566async def do_select(1567 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1568why, one step back1568 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1569–1574why, one step back1569 *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)15731574Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1575why, one step back1575@pass_contextMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1576why, one step back1576def sync_do_reject(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1577–1578why, one step back1577 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1578) -> "t.Iterator[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1579–1597why, one step back1579 """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 back1598 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 back15991600Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1601why, one step back1601@async_variant(sync_do_reject) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1602–1603why, one step back1602async def do_reject(1603 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1604why, one step back1604 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1605–1610why, one step back1605 *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)16091610Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1611why, one step back1611@pass_contextMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1612why, one step back1612def sync_do_selectattr(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1613–1614why, one step back1613 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1614) -> "t.Iterator[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1615–1632why, one step back1615 """Filters a sequence of objects by applying a test to the specified1616 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:: python1632Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1633–1634why, one step back1633 (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 back16351636 .. versionadded:: 2.71637 """Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1638why, one step back1638 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 back16391640Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1641why, one step back1641@async_variant(sync_do_selectattr) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1642–1643why, one step back1642async def do_selectattr(1643 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1644why, one step back1644 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1645–1650why, one step back1645 *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)16491650Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1651why, one step back1651@pass_contextMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1652why, one step back1652def sync_do_rejectattr(Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1653–1654why, one step back1653 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1654) -> "t.Iterator[V]":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1655–1670why, one step back1655 """Filters a sequence of objects by applying a test to the specified1656 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:: python1670Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1671–1672why, one step back1671 (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 back16731674 .. versionadded:: 2.71675 """Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1676why, one step back1676 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 back16771678Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1679why, one step back1679@async_variant(sync_do_rejectattr) # type: ignoreMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1680–1681why, one step back1680async def do_rejectattr(1681 context: "Context",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1682why, one step back1682 value: "t.AsyncIterable[V] | t.Iterable[V]",Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1683–1688why, one step back1683 *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)16871688Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1689why, one step back1689@pass_eval_contextMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1690why, one step back1690def do_tojson(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1691why, one step back1691 eval_ctx: "EvalContext", value: t.Any, indent: int | None = NoneMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1692why, one step back1692) -> Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1693–1717why, one step back1693 """Serialize an object to a string of JSON, and mark it safe to1694 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)17161717Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1718why, one step back1718def prepare_map(Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1719why, one step back1719 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 back1720) -> 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 back1722 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 back1724update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1725–1728why, one step back1725 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 back1729update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1730–1732why, one step back1730 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 back1733 name = args[0]1734 args = args[1:]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1735why, one step back1735 except LookupError:Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 1736why, one step back1736 raise FilterArgumentError("map requires a filter argument") from Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1737why, one step back1737Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1738why, one step back1738 def func(item: t.Any) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1739–1742why, one step back1739 return context.environment.call_filter(1740 name, item, args, kwargs, context=context1741 )1742Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1743why, one step back1743 return funcupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1744–1745why, one step back17441745Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1746–1747why, one step back1746def prepare_select_or_reject(1747 context: "Context",Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 1748–1749why, one step back1748 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 back1750 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 back1753 if lookup_attr:1754 try:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1755why, one step back1755 attr = args[0]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1756why, one step back1756 except LookupError:Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 1757why, one step back1757 raise FilterArgumentError("Missing parameter for attribute name") from NoneMerge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1758why, one step back1758update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1759–1763why, one step back1759 transfunc = make_attrgetter(context.environment, attr)1760 off = 11761 else:1762 off = 01763Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1764why, one step back1764 def transfunc(x: V) -> V:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1765–1767why, one step back1765 return x17661767 try:Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1768–1769why, one step back1768 name = args[off]1769 args = args[1 + off :]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1770why, one step back1770Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1771why, one step back1771 def func(item: t.Any) -> t.Any:Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1772why, one step back1772 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 back17731774 except LookupError:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1775why, one step back1775 func = bool # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1776why, one step back1776Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
line 1777why, one step back1777 return lambda item: modfunc(func(transfunc(item)))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1778–1779why, one step back17781779Merge pull request #1384 from pallets/typing-filters-testsDavid Lordbefore adoption7bea919
lines 1780–1782why, one step back1780def 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 back1783 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 back1785 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 back1792 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 back1798 value: "t.AsyncIterable[V] | t.Iterable[V]",Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 1799–1800why, one step back1799 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 back1801 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 back1808 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 back1837 "items": do_items,update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1838–1867why, one step back1838 "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}