Skip to content
Myr

filters.py

This file

Path

src/jinja2/filters.py

1,867 lines · 53.3 KiB · Python

Last changed by

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

History of this file

Take it

1"""Built-in template filters used with the ``|`` operator."""23import math4import random5import re6import typing7import typing as t8from collections import abc9from inspect import getattr_static10from itertools import chain11from itertools import groupby1213from markupsafe import escape14from markupsafe import Markup15from markupsafe import soft_str1617from .async_utils import async_variant18from .async_utils import auto_aiter19from .async_utils import auto_await20from .async_utils import auto_to_list21from .exceptions import FilterArgumentError22from .runtime import Undefined23from .utils import htmlsafe_json_dumps24from .utils import pass_context25from .utils import pass_environment26from .utils import pass_eval_context27from .utils import pformat28from .utils import url_quote29from .utils import urlize3031if t.TYPE_CHECKING:32    import typing_extensions as te3334    from .environment import Environment35    from .nodes import EvalContext36    from .runtime import Context37    from .sandbox import SandboxedEnvironment  # noqa: F4013839    class HasHTML(te.Protocol):40        def __html__(self) -> str:41            pass424344F = t.TypeVar("F", bound=t.Callable[..., t.Any])45K = t.TypeVar("K")46V = t.TypeVar("V")474849def ignore_case(value: V) -> V:50    """For use as a postprocessor for :func:`make_attrgetter`. Converts strings51    to lowercase and returns other types as-is."""52    if isinstance(value, str):53        return t.cast(V, value.lower())5455    return value565758def make_attrgetter(59    environment: "Environment",60    attribute: str | int | None,61    postprocess: t.Callable[[t.Any], t.Any] | None = None,62    default: t.Any | None = None,63) -> t.Callable[[t.Any], t.Any]:64    """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    """69    parts = _prepare_attribute_parts(attribute)7071    def attrgetter(item: t.Any) -> t.Any:72        for part in parts:73            item = environment.getitem(item, part)7475            if default is not None and isinstance(item, Undefined):76                item = default7778        if postprocess is not None:79            item = postprocess(item)8081        return item8283    return attrgetter848586def make_multi_attrgetter(87    environment: "Environment",88    attribute: str | int | None,89    postprocess: t.Callable[[t.Any], t.Any] | None = None,90) -> t.Callable[[t.Any], list[t.Any]]:91    """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    """101    if isinstance(attribute, str):102        split: t.Sequence[str | int | None] = attribute.split(",")103    else:104        split = [attribute]105106    parts = [_prepare_attribute_parts(item) for item in split]107108    def attrgetter(item: t.Any) -> list[t.Any]:109        items = [None] * len(parts)110111        for i, attribute_part in enumerate(parts):112            item_i = item113114            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_i121122        return items123124    return attrgetter125126127def _prepare_attribute_parts(128    attr: str | int | None,129) -> list[str | int]:130    if attr is None:131        return []132133    if isinstance(attr, str):134        return [int(x) if x.isdigit() else x for x in attr.split(".")]135136    return [attr]137138139def do_forceescape(value: "str | HasHTML") -> Markup:140    """Enforce HTML escaping.  This will probably double escape variables."""141    if hasattr(value, "__html__"):142        value = t.cast("HasHTML", value).__html__()143144    return escape(str(value))145146147def do_urlencode(148    value: str | t.Mapping[str, t.Any] | t.Iterable[tuple[str, t.Any]],149) -> str:150    """Quote data for use in a URL path or query using UTF-8.151152    Basic wrapper around :func:`urllib.parse.quote` when given a153    string, or :func:`urllib.parse.urlencode` for a dict or iterable.154155    :param value: Data to quote. A string will be quoted directly. A156        dict or iterable of ``(key, value)`` pairs will be joined as a157        query string.158159    When given a string, "/" is not quoted. HTTP servers treat "/" and160    "%2F" equivalently in paths. If you need quoted slashes, use the161    ``|replace("/", "%2F")`` filter.162163    .. versionadded:: 2.7164    """165    if isinstance(value, str) or not isinstance(value, abc.Iterable):166        return url_quote(value)167168    if isinstance(value, dict):169        items: t.Iterable[tuple[str, t.Any]] = value.items()170    else:171        items = value  # type: ignore172173    return "&".join(174        f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items175    )176177178@pass_eval_context179def do_replace(180    eval_ctx: "EvalContext", s: str, old: str, new: str, count: int | None = None181) -> str:182    """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 = -1198199    if not eval_ctx.autoescape:200        return str(s).replace(str(old), str(new), count)201202    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)210211    return s.replace(soft_str(old), soft_str(new), count)212213214def do_upper(s: str) -> str:215    """Convert a value to uppercase."""216    return soft_str(s).upper()217218219def do_lower(s: str) -> str:220    """Convert a value to lowercase."""221    return soft_str(s).lower()222223224def do_items(value: t.Mapping[K, V] | Undefined) -> t.Iterator[tuple[K, V]]:225    """Return an iterator over the ``(key, value)`` items of a mapping.226227    ``x|items`` is the same as ``x.items()``, except if ``x`` is228    undefined an empty iterator is returned.229230    This filter is useful if you expect the template to be rendered with231    an implementation of Jinja in another programming language that does232    not have a ``.items()`` method on its mapping type.233234    .. code-block:: html+jinja235236        <dl>237        {% for key, value in my_dict|items %}238            <dt>{{ key }}239            <dd>{{ value }}240        {% endfor %}241        </dl>242243    .. versionadded:: 3.1244    """245    if isinstance(value, Undefined):246        return247248    if not isinstance(value, abc.Mapping):249        raise TypeError("Can only get item pairs from a mapping.")250251    yield from value.items()252253254# 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)257258259@pass_eval_context260def do_xmlattr(261    eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True262) -> str:263    """Create an SGML/XML attribute string based on the items in a dict.264265    **Values** that are neither ``none`` nor ``undefined`` are automatically266    escaped, safely allowing untrusted user input.267268    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.273274    .. 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.291292    .. versionchanged:: 3.1.4293        Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign294        are not allowed.295296    .. versionchanged:: 3.1.3297        Keys with spaces are not allowed.298    """299    items = []300301    for key, value in d.items():302        if value is None or isinstance(value, Undefined):303            continue304305        if _attr_key_re.search(key) is not None:306            raise ValueError(f"Invalid character in attribute name: {key!r}")307308        items.append(f'{escape(key)}="{escape(value)}"')309310    rv = " ".join(items)311312    if autospace and rv:313        rv = " " + rv314315    if eval_ctx.autoescape:316        rv = Markup(rv)317318    return rv319320321def do_capitalize(s: str) -> str:322    """Capitalize a value. The first character will be uppercase, all others323    lowercase.324    """325    return soft_str(s).capitalize()326327328_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")329330331def do_title(s: str) -> str:332    """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    )342343344def do_dictsort(345    value: t.Mapping[K, V],346    case_sensitive: bool = False,347    by: 'te.Literal["key", "value"]' = "key",348    reverse: bool = False,349) -> list[tuple[K, V]]:350    """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.352353    .. 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"')373374    def sort_func(item: tuple[t.Any, t.Any]) -> t.Any:375        value = item[pos]376377        if not case_sensitive:378            value = ignore_case(value)379380        return value381382    return sorted(value.items(), key=sort_func, reverse=reverse)383384385@pass_environment386def do_sort(387    environment: "Environment",388    value: "t.Iterable[V]",389    reverse: bool = False,390    case_sensitive: bool = False,391    attribute: str | int | None = None,392) -> "list[V]":393    """Sort an iterable using Python's :func:`sorted`.394395    .. sourcecode:: jinja396397        {% for city in cities|sort %}398            ...399        {% endfor %}400401    :param reverse: Sort descending instead of ascending.402    :param case_sensitive: When sorting strings, sort upper and lower403        case separately.404    :param attribute: When sorting objects or dicts, an attribute or405        key to sort by. Can use dot notation like ``"address.city"``.406        Can be a list of attributes like ``"age,name"``.407408    The sort is stable, it does not change the relative order of409    elements that compare equal. This makes it is possible to chain410    sorts on different attributes and ordering.411412    .. sourcecode:: jinja413414        {% for user in users|sort(attribute="name")415            |sort(reverse=true, attribute="age") %}416            ...417        {% endfor %}418419    As a shortcut to chaining when the direction is the same for all420    attributes, pass a comma separate list of attributes.421422    .. sourcecode:: jinja423424        {% for user in users|sort(attribute="age,name") %}425            ...426        {% endfor %}427428    .. versionchanged:: 2.11.0429        The ``attribute`` parameter can be a comma separated list of430        attributes, e.g. ``"age,name"``.431432    .. versionchanged:: 2.6433       The ``attribute`` parameter was added.434    """435    key_func = make_multi_attrgetter(436        environment, attribute, postprocess=ignore_case if not case_sensitive else None437    )438    return sorted(value, key=key_func, reverse=reverse)439440441@pass_environment442def sync_do_unique(443    environment: "Environment",444    value: "t.Iterable[V]",445    case_sensitive: bool = False,446    attribute: str | int | None = None,447) -> "t.Iterator[V]":448    """Returns a list of unique items from the given iterable.449450    .. sourcecode:: jinja451452        {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}453            -> ['foo', 'bar', 'foobar']454455    The unique items are yielded in the same order as their first occurrence in456    the iterable passed to the filter.457458    :param case_sensitive: Treat upper and lower case strings as distinct.459    :param attribute: Filter objects with unique values for this attribute.460    """461    getter = make_attrgetter(462        environment, attribute, postprocess=ignore_case if not case_sensitive else None463    )464    seen = set()465466    for item in value:467        key = getter(item)468469        if key not in seen:470            seen.add(key)471            yield item472473474@async_variant(sync_do_unique)  # type: ignore475async def do_unique(476    environment: "Environment",477    value: "t.AsyncIterable[V] | t.Iterable[V]",478    case_sensitive: bool = False,479    attribute: str | int | None = None,480) -> "t.Iterator[V]":481    return sync_do_unique(482        environment, await auto_to_list(value), case_sensitive, attribute483    )484485486def _min_or_max(487    environment: "Environment",488    value: "t.Iterable[V]",489    func: "t.Callable[..., V]",490    case_sensitive: bool,491    attribute: str | int | None,492) -> "V | Undefined":493    it = iter(value)494495    try:496        first = next(it)497    except StopIteration:498        return environment.undefined("No aggregated item, sequence was empty.")499500    key_func = make_attrgetter(501        environment, attribute, postprocess=ignore_case if not case_sensitive else None502    )503    return func(chain([first], it), key=key_func)504505506@pass_environment507def do_min(508    environment: "Environment",509    value: "t.Iterable[V]",510    case_sensitive: bool = False,511    attribute: str | int | None = None,512) -> "V | Undefined":513    """Return the smallest item from the sequence.514515    .. sourcecode:: jinja516517        {{ [1, 2, 3]|min }}518            -> 1519520    :param case_sensitive: Treat upper and lower case strings as distinct.521    :param attribute: Get the object with the min value of this attribute.522    """523    return _min_or_max(environment, value, min, case_sensitive, attribute)524525526@pass_environment527def do_max(528    environment: "Environment",529    value: "t.Iterable[V]",530    case_sensitive: bool = False,531    attribute: str | int | None = None,532) -> "V | Undefined":533    """Return the largest item from the sequence.534535    .. sourcecode:: jinja536537        {{ [1, 2, 3]|max }}538            -> 3539540    :param case_sensitive: Treat upper and lower case strings as distinct.541    :param attribute: Get the object with the max value of this attribute.542    """543    return _min_or_max(environment, value, max, case_sensitive, attribute)544545546def do_default(547    value: V,548    default_value: V = "",  # type: ignore549    boolean: bool = False,550) -> V:551    """If the value is undefined it will return the passed default value,552    otherwise the value of the variable:553554    .. sourcecode:: jinja555556        {{ my_variable|default('my_variable is not defined') }}557558    This will output the value of ``my_variable`` if the variable was559    defined, otherwise ``'my_variable is not defined'``. If you want560    to use default with variables that evaluate to false you have to561    set the second parameter to `true`:562563    .. sourcecode:: jinja564565        {{ ''|default('the string was empty', true) }}566567    .. versionchanged:: 2.11568       It's now possible to configure the :class:`~jinja2.Environment` with569       :class:`~jinja2.ChainableUndefined` to make the `default` filter work570       on nested elements and attributes that may contain undefined values571       in the chain without getting an :exc:`~jinja2.UndefinedError`.572    """573    if isinstance(value, Undefined) or (boolean and not value):574        return default_value575576    return value577578579@pass_eval_context580def sync_do_join(581    eval_ctx: "EvalContext",582    value: t.Iterable[t.Any],583    d: str = "",584    attribute: str | int | None = None,585) -> str:586    """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 = False619620        for idx, item in enumerate(value):621            if hasattr(item, "__html__"):622                do_escape = True623            else:624                value[idx] = str(item)625626        if do_escape:627            d = escape(d)628        else:629            d = str(d)630631        return d.join(value)632633    # no html involved, to normal joining634    return soft_str(d).join(map(soft_str, value))635636637@async_variant(sync_do_join)  # type: ignore638async def do_join(639    eval_ctx: "EvalContext",640    value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],641    d: str = "",642    attribute: str | int | None = None,643) -> str:644    return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)645646647def do_center(value: str, width: int = 80) -> str:648    """Centers the value in a field of a given width."""649    return soft_str(value).center(width)650651652@pass_environment653def sync_do_first(environment: "Environment", seq: "t.Iterable[V]") -> "V | Undefined":654    """Return the first item of a sequence."""655    try:656        return next(iter(seq))657    except StopIteration:658        return environment.undefined("No first item, sequence was empty.")659660661@async_variant(sync_do_first)  # type: ignore662async def do_first(663    environment: "Environment", seq: "t.AsyncIterable[V] | t.Iterable[V]"664) -> "V | Undefined":665    try:666        return await auto_aiter(seq).__anext__()667    except StopAsyncIteration:668        return environment.undefined("No first item, sequence was empty.")669670671@pass_environment672def do_last(environment: "Environment", seq: "t.Reversible[V]") -> "V | Undefined":673    """Return the last item of a sequence.674675    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.")686687688# No async do_last, it may not be safe in async mode.689690691@pass_context692def do_random(context: "Context", seq: "t.Sequence[V]") -> "V | Undefined":693    """Return a random item from the sequence."""694    try:695        return random.choice(seq)696    except IndexError:697        return context.environment.undefined("No random item, sequence was empty.")698699700def do_filesizeformat(value: str | float | int, binary: bool = False) -> str:701    """Format the value like a 'human-readable' file size (i.e. 13 kB,702    4.1 MB, 102 Bytes, etc).  Per default decimal prefixes are used (Mega,703    Giga, etc.), if the second parameter is set to `True` the binary704    prefixes are used (Mebi, Gibi).705    """706    bytes = float(value)707    base = 1024 if binary else 1000708    prefixes = [709        ("KiB" if binary else "kB"),710        ("MiB" if binary else "MB"),711        ("GiB" if binary else "GB"),712        ("TiB" if binary else "TB"),713        ("PiB" if binary else "PB"),714        ("EiB" if binary else "EB"),715        ("ZiB" if binary else "ZB"),716        ("YiB" if binary else "YB"),717    ]718719    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)726727            if bytes < unit:728                return f"{base * bytes / unit:.1f} {prefix}"729730        return f"{base * bytes / unit:.1f} {prefix}"731732733def do_pprint(value: t.Any) -> str:734    """Pretty print a variable. Useful for debugging."""735    return pformat(value)736737738_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")739740741@pass_eval_context742def do_urlize(743    eval_ctx: "EvalContext",744    value: str,745    trim_url_limit: int | None = None,746    nofollow: bool = False,747    target: str | None = None,748    rel: str | None = None,749    extra_schemes: t.Iterable[str] | None = None,750) -> str:751    """Convert URLs in text into clickable links.752753    This may not recognize links in some situations. Usually, a more754    comprehensive formatter, such as a Markdown library, is a better755    choice.756757    Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email758    addresses. Links with trailing punctuation (periods, commas, closing759    parentheses) and leading punctuation (opening parentheses) are760    recognized excluding the punctuation. Email addresses that include761    header fields are not recognized (for example,762    ``mailto:address@example.com?cc=copy@example.com``).763764    :param value: Original text containing URLs to link.765    :param trim_url_limit: Shorten displayed URL values to this length.766    :param nofollow: Add the ``rel=nofollow`` attribute to links.767    :param target: Add the ``target`` attribute to links.768    :param rel: Add the ``rel`` attribute to links.769    :param extra_schemes: Recognize URLs that start with these schemes770        in addition to the default behavior. Defaults to771        ``env.policies["urlize.extra_schemes"]``, which defaults to no772        extra schemes.773774    .. versionchanged:: 3.0775        The ``extra_schemes`` parameter was added.776777    .. versionchanged:: 3.0778        Generate ``https://`` links for URLs without a scheme.779780    .. versionchanged:: 3.0781        The parsing rules were updated. Recognize email addresses with782        or without the ``mailto:`` scheme. Validate IP addresses. Ignore783        parentheses and brackets in more cases.784785    .. versionchanged:: 2.8786       The ``target`` parameter was added.787    """788    policies = eval_ctx.environment.policies789    rel_parts = set((rel or "").split())790791    if nofollow:792        rel_parts.add("nofollow")793794    rel_parts.update((policies["urlize.rel"] or "").split())795    rel = " ".join(sorted(rel_parts)) or None796797    if target is None:798        target = policies["urlize.target"]799800    if extra_schemes is None:801        extra_schemes = policies["urlize.extra_schemes"] or ()802803    for scheme in extra_schemes:804        if _uri_scheme_re.fullmatch(scheme) is None:805            raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")806807    rv = urlize(808        value,809        trim_url_limit=trim_url_limit,810        rel=rel,811        target=target,812        extra_schemes=extra_schemes,813    )814815    if eval_ctx.autoescape:816        rv = Markup(rv)817818    return rv819820821def do_indent(822    s: str, width: int | str = 4, first: bool = False, blank: bool = False823) -> str:824    """Return a copy of the string with each line indented by 4 spaces. The825    first line and blank lines are not indented by default.826827    :param width: Number of spaces, or a string, to indent by.828    :param first: Don't skip indenting the first line.829    :param blank: Don't skip indenting empty lines.830831    .. versionchanged:: 3.0832        ``width`` can be a string.833834    .. versionchanged:: 2.10835        Blank lines are not indented by default.836837        Rename the ``indentfirst`` argument to ``first``.838    """839    if isinstance(width, str):840        indention = width841    else:842        indention = " " * width843844    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 rv867868869@pass_environment870def do_truncate(871    env: "Environment",872    s: str,873    length: int = 255,874    killwords: bool = False,875    end: str = "...",876    leeway: int | None = None,877) -> str:878    """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"]903904    assert length >= len(end), f"expected length >= {len(end)}, got {length}"905    assert leeway >= 0, f"expected leeway >= 0, got {leeway}"906907    if len(s) <= length + leeway:908        return s909910    if killwords:911        return s[: length - len(end)] + end912913    result = s[: length - len(end)].rsplit(" ", 1)[0]914    return result + end915916917@pass_environment918def do_wordwrap(919    environment: "Environment",920    s: str,921    width: int = 79,922    break_long_words: bool = True,923    wrapstring: str | None = None,924    break_on_hyphens: bool = True,925) -> str:926    """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 textwrap948949    if wrapstring is None:950        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    )971972973_word_re = re.compile(r"\w+")974975976def do_wordcount(s: str) -> int:977    """Count the words in that string."""978    return len(_word_re.findall(soft_str(s)))979980981def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:982    """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)993994        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))999        except (TypeError, ValueError, OverflowError):1000            return default100110021003def do_float(value: t.Any, default: float = 0.0) -> float:1004    """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 default101210131014def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:1015    """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        )10381039    return soft_str(value) % (kwargs or args)104010411042def do_trim(value: str, chars: str | None = None) -> str:1043    """Strip leading and trailing characters, by default whitespace."""1044    return soft_str(value).strip(chars)104510461047def do_striptags(value: "str | HasHTML") -> str:1048    """Strip SGML/XML tags and replace adjacent whitespace by one space."""1049    if hasattr(value, "__html__"):1050        value = t.cast("HasHTML", value).__html__()10511052    return Markup(str(value)).striptags()105310541055def sync_do_slice(1056    value: "t.Collection[V]", slices: int, fill_with: "V | None" = None1057) -> "t.Iterator[list[V]]":1058    """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 = 010821083    for slice_number in range(slices):1084        start = offset + slice_number * items_per_slice10851086        if slice_number < slices_with_extra:1087            offset += 110881089        end = offset + (slice_number + 1) * items_per_slice1090        tmp = seq[start:end]10911092        if fill_with is not None and slice_number >= slices_with_extra:1093            tmp.append(fill_with)10941095        yield tmp109610971098@async_variant(sync_do_slice)  # type: ignore1099async def do_slice(1100    value: "t.AsyncIterable[V] | t.Iterable[V]",1101    slices: int,1102    fill_with: t.Any | None = None,1103) -> "t.Iterator[list[V]]":1104    return sync_do_slice(await auto_to_list(value), slices, fill_with)110511061107def do_batch(1108    value: "t.Iterable[V]", linecount: int, fill_with: "V | None" = None1109) -> "t.Iterator[list[V]]":1110    """1111    A filter that batches items. It works pretty much like `slice`1112    just the other way round. It returns a list of lists with the1113    given number of items. If you provide a second parameter this1114    is used to fill up missing items. See this example:11151116    .. sourcecode:: html+jinja11171118        <table>1119        {%- for row in items|batch(3, '&nbsp;') %}1120          <tr>1121          {%- for column in row %}1122            <td>{{ column }}</td>1123          {%- endfor %}1124          </tr>1125        {%- endfor %}1126        </table>1127    """1128    tmp: list[V] = []11291130    for item in value:1131        if len(tmp) == linecount:1132            yield tmp1133            tmp = []11341135        tmp.append(item)11361137    if tmp:1138        if fill_with is not None and len(tmp) < linecount:1139            tmp += [fill_with] * (linecount - len(tmp))11401141        yield tmp114211431144def do_round(1145    value: float,1146    precision: int = 0,1147    method: 'te.Literal["common", "ceil", "floor"]' = "common",1148) -> float:1149    """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")11761177    if method == "common":1178        return round(value, precision)11791180    func = getattr(math, method)1181    return t.cast(float, func(value * (10**precision)) / (10**precision))118211831184class _GroupTuple(t.NamedTuple):1185    grouper: t.Any1186    list: list[t.Any]11871188    # Use the regular tuple repr to hide this subclass if users print1189    # out the value during debugging.1190    def __repr__(self) -> str:1191        return tuple.__repr__(self)11921193    def __str__(self) -> str:1194        return tuple.__str__(self)119511961197@pass_environment1198def sync_do_groupby(1199    environment: "Environment",1200    value: "t.Iterable[V]",1201    attribute: str | int,1202    default: t.Any | None = None,1203    case_sensitive: bool = False,1204) -> "list[_GroupTuple]":1205    """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>12341235    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>12431244    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.12551256    .. versionchanged:: 3.01257        Added the ``default`` parameter.12581259    .. versionchanged:: 2.61260        The attribute supports dot notation for nested access.1261    """1262    expr = make_attrgetter(1263        environment,1264        attribute,1265        postprocess=ignore_case if not case_sensitive else None,1266        default=default,1267    )1268    out = [1269        _GroupTuple(key, list(values))1270        for key, values in groupby(sorted(value, key=expr), expr)1271    ]12721273    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]12771278    return out127912801281@async_variant(sync_do_groupby)  # type: ignore1282async def do_groupby(1283    environment: "Environment",1284    value: "t.AsyncIterable[V] | t.Iterable[V]",1285    attribute: str | int,1286    default: t.Any | None = None,1287    case_sensitive: bool = False,1288) -> "list[_GroupTuple]":1289    expr = make_attrgetter(1290        environment,1291        attribute,1292        postprocess=ignore_case if not case_sensitive else None,1293        default=default,1294    )1295    out = [1296        _GroupTuple(key, await auto_to_list(values))1297        for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)1298    ]12991300    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 out130613071308@pass_environment1309def sync_do_sum(1310    environment: "Environment",1311    iterable: "t.Iterable[V]",1312    attribute: str | int | None = None,1313    start: V = 0,  # type: ignore1314) -> V:1315    """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.61326       The ``attribute`` parameter was added to allow summing up over1327       attributes.  Also the ``start`` parameter was moved on to the right.1328    """1329    if attribute is not None:1330        iterable = map(make_attrgetter(environment, attribute), iterable)13311332    return sum(iterable, start)  # type: ignore[no-any-return, call-overload]133313341335@async_variant(sync_do_sum)  # type: ignore1336async def do_sum(1337    environment: "Environment",1338    iterable: "t.AsyncIterable[V] | t.Iterable[V]",1339    attribute: str | int | None = None,1340    start: V = 0,  # type: ignore1341) -> V:1342    rv = start13431344    if attribute is not None:1345        func = make_attrgetter(environment, attribute)1346    else:13471348        def func(x: V) -> V:1349            return x13501351    async for item in auto_aiter(iterable):1352        rv += func(item)13531354    return rv135513561357def sync_do_list(value: "t.Iterable[V]") -> "list[V]":1358    """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)136213631364@async_variant(sync_do_list)  # type: ignore1365async def do_list(value: "t.AsyncIterable[V] | t.Iterable[V]") -> "list[V]":1366    return await auto_to_list(value)136713681369def do_mark_safe(value: str) -> Markup:1370    """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)137413751376def do_mark_unsafe(value: str) -> str:1377    """Mark a value as unsafe.  This is the reverse operation for :func:`safe`."""1378    return str(value)137913801381@typing.overload1382def do_reverse(value: str) -> str: ...138313841385@typing.overload1386def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...138713881389def do_reverse(value: str | t.Iterable[V]) -> str | t.Iterable[V]:1390    """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]13951396    try:1397        return reversed(value)  # type: ignore1398    except TypeError:1399        try:1400            rv = list(value)1401            rv.reverse()1402            return rv1403        except TypeError as e:1404            raise FilterArgumentError("argument must be iterable") from e140514061407@pass_environment1408def do_attr(environment: "Environment", obj: t.Any, name: str) -> Undefined | t.Any:1409    """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.14121413    See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1414    """1415    # Environment.getattr will fall back to obj[name] if obj.name doesn't exist.1416    # But we want to call env.getattr to get behavior such as sandboxing.1417    # Determine if the attr exists first, so we know the fallback won't trigger.1418    try:1419        # This avoids executing properties/descriptors, but misses __getattr__1420        # and __getattribute__ dynamic attrs.1421        getattr_static(obj, name)1422    except AttributeError:1423        # This finds dynamic attrs, and we know it's not a descriptor at this point.1424        if not hasattr(obj, name):1425            return environment.undefined(obj=obj, name=name)14261427    return environment.getattr(obj, name)142814291430@typing.overload1431def sync_do_map(1432    context: "Context",1433    value: t.Iterable[t.Any],1434    name: str,1435    *args: t.Any,1436    **kwargs: t.Any,1437) -> t.Iterable[t.Any]: ...143814391440@typing.overload1441def sync_do_map(1442    context: "Context",1443    value: t.Iterable[t.Any],1444    *,1445    attribute: str = ...,1446    default: t.Any | None = None,1447) -> t.Iterable[t.Any]: ...144814491450@pass_context1451def sync_do_map(1452    context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any1453) -> t.Iterable[t.Any]:1454    """Applies a filter on a sequence of objects or looks up an attribute.1455    This is useful when dealing with lists of objects but you are really1456    only interested in a certain value of it.14571458    The basic usage is mapping on an attribute.  Imagine you have a list1459    of users but you are only interested in a list of usernames:14601461    .. sourcecode:: jinja14621463        Users on this page: {{ users|map(attribute='username')|join(', ') }}14641465    You can specify a ``default`` value to use if an object in the list1466    does not have the given attribute.14671468    .. sourcecode:: jinja14691470        {{ users|map(attribute="username", default="Anonymous")|join(", ") }}14711472    Alternatively you can let it invoke a filter by passing the name of the1473    filter and the arguments afterwards.  A good example would be applying a1474    text conversion filter on a sequence:14751476    .. sourcecode:: jinja14771478        Users on this page: {{ titles|map('lower')|join(', ') }}14791480    Similar to a generator comprehension such as:14811482    .. code-block:: python14831484        (u.username for u in users)1485        (getattr(u, "username", "Anonymous") for u in users)1486        (do_lower(x) for x in titles)14871488    .. versionchanged:: 2.11.01489        Added the ``default`` parameter.14901491    .. versionadded:: 2.71492    """1493    if value:1494        func = prepare_map(context, args, kwargs)14951496        for item in value:1497            yield func(item)149814991500@typing.overload1501def do_map(1502    context: "Context",1503    value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1504    name: str,1505    *args: t.Any,1506    **kwargs: t.Any,1507) -> t.Iterable[t.Any]: ...150815091510@typing.overload1511def do_map(1512    context: "Context",1513    value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1514    *,1515    attribute: str = ...,1516    default: t.Any | None = None,1517) -> t.Iterable[t.Any]: ...151815191520@async_variant(sync_do_map)  # type: ignore1521async def do_map(1522    context: "Context",1523    value: t.AsyncIterable[t.Any] | t.Iterable[t.Any],1524    *args: t.Any,1525    **kwargs: t.Any,1526) -> t.AsyncIterable[t.Any]:1527    if value:1528        func = prepare_map(context, args, kwargs)15291530        async for item in auto_aiter(value):1531            yield await auto_await(func(item))153215331534@pass_context1535def sync_do_select(1536    context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1537) -> "t.Iterator[V]":1538    """Filters a sequence of objects by applying a test to each object,1539    and only selecting the objects with the test succeeding.15401541    If no test is specified, each object will be evaluated as a boolean.15421543    Example usage:15441545    .. sourcecode:: jinja15461547        {{ numbers|select("odd") }}1548        {{ numbers|select("odd") }}1549        {{ numbers|select("divisibleby", 3) }}1550        {{ numbers|select("lessthan", 42) }}1551        {{ strings|select("equalto", "mystring") }}15521553    Similar to a generator comprehension such as:15541555    .. code-block:: python15561557        (n for n in numbers if test_odd(n))1558        (n for n in numbers if test_divisibleby(n, 3))15591560    .. versionadded:: 2.71561    """1562    return select_or_reject(context, value, args, kwargs, lambda x: x, False)156315641565@async_variant(sync_do_select)  # type: ignore1566async def do_select(1567    context: "Context",1568    value: "t.AsyncIterable[V] | t.Iterable[V]",1569    *args: t.Any,1570    **kwargs: t.Any,1571) -> "t.AsyncIterator[V]":1572    return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)157315741575@pass_context1576def sync_do_reject(1577    context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1578) -> "t.Iterator[V]":1579    """Filters a sequence of objects by applying a test to each object,1580    and rejecting the objects with the test succeeding.15811582    If no test is specified, each object will be evaluated as a boolean.15831584    Example usage:15851586    .. sourcecode:: jinja15871588        {{ numbers|reject("odd") }}15891590    Similar to a generator comprehension such as:15911592    .. code-block:: python15931594        (n for n in numbers if not test_odd(n))15951596    .. versionadded:: 2.71597    """1598    return select_or_reject(context, value, args, kwargs, lambda x: not x, False)159916001601@async_variant(sync_do_reject)  # type: ignore1602async def do_reject(1603    context: "Context",1604    value: "t.AsyncIterable[V] | t.Iterable[V]",1605    *args: t.Any,1606    **kwargs: t.Any,1607) -> "t.AsyncIterator[V]":1608    return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)160916101611@pass_context1612def sync_do_selectattr(1613    context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1614) -> "t.Iterator[V]":1615    """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:: python16321633        (user for user in users if user.is_active)1634        (user for user in users if test_none(user.email))16351636    .. versionadded:: 2.71637    """1638    return select_or_reject(context, value, args, kwargs, lambda x: x, True)163916401641@async_variant(sync_do_selectattr)  # type: ignore1642async def do_selectattr(1643    context: "Context",1644    value: "t.AsyncIterable[V] | t.Iterable[V]",1645    *args: t.Any,1646    **kwargs: t.Any,1647) -> "t.AsyncIterator[V]":1648    return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)164916501651@pass_context1652def sync_do_rejectattr(1653    context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1654) -> "t.Iterator[V]":1655    """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:: python16701671        (user for user in users if not user.is_active)1672        (user for user in users if not test_none(user.email))16731674    .. versionadded:: 2.71675    """1676    return select_or_reject(context, value, args, kwargs, lambda x: not x, True)167716781679@async_variant(sync_do_rejectattr)  # type: ignore1680async def do_rejectattr(1681    context: "Context",1682    value: "t.AsyncIterable[V] | t.Iterable[V]",1683    *args: t.Any,1684    **kwargs: t.Any,1685) -> "t.AsyncIterator[V]":1686    return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)168716881689@pass_eval_context1690def do_tojson(1691    eval_ctx: "EvalContext", value: t.Any, indent: int | None = None1692) -> Markup:1693    """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)171617171718def prepare_map(1719    context: "Context", args: tuple[t.Any, ...], kwargs: dict[str, t.Any]1720) -> t.Callable[[t.Any], t.Any]:1721    if not args and "attribute" in kwargs:1722        attribute = kwargs.pop("attribute")1723        default = kwargs.pop("default", None)17241725        if kwargs:1726            raise FilterArgumentError(1727                f"Unexpected keyword argument {next(iter(kwargs))!r}"1728            )17291730        func = make_attrgetter(context.environment, attribute, default=default)1731    else:1732        try:1733            name = args[0]1734            args = args[1:]1735        except LookupError:1736            raise FilterArgumentError("map requires a filter argument") from None17371738        def func(item: t.Any) -> t.Any:1739            return context.environment.call_filter(1740                name, item, args, kwargs, context=context1741            )17421743    return func174417451746def prepare_select_or_reject(1747    context: "Context",1748    args: tuple[t.Any, ...],1749    kwargs: dict[str, t.Any],1750    modfunc: t.Callable[[t.Any], t.Any],1751    lookup_attr: bool,1752) -> t.Callable[[t.Any], t.Any]:1753    if lookup_attr:1754        try:1755            attr = args[0]1756        except LookupError:1757            raise FilterArgumentError("Missing parameter for attribute name") from None17581759        transfunc = make_attrgetter(context.environment, attr)1760        off = 11761    else:1762        off = 017631764        def transfunc(x: V) -> V:1765            return x17661767    try:1768        name = args[off]1769        args = args[1 + off :]17701771        def func(item: t.Any) -> t.Any:1772            return context.environment.call_test(name, item, args, kwargs, context)17731774    except LookupError:1775        func = bool  # type: ignore17761777    return lambda item: modfunc(func(transfunc(item)))177817791780def select_or_reject(1781    context: "Context",1782    value: "t.Iterable[V]",1783    args: tuple[t.Any, ...],1784    kwargs: dict[str, t.Any],1785    modfunc: t.Callable[[t.Any], t.Any],1786    lookup_attr: bool,1787) -> "t.Iterator[V]":1788    if value:1789        func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)17901791        for item in value:1792            if func(item):1793                yield item179417951796async def async_select_or_reject(1797    context: "Context",1798    value: "t.AsyncIterable[V] | t.Iterable[V]",1799    args: tuple[t.Any, ...],1800    kwargs: dict[str, t.Any],1801    modfunc: t.Callable[[t.Any], t.Any],1802    lookup_attr: bool,1803) -> "t.AsyncIterator[V]":1804    if value:1805        func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)18061807        async for item in auto_aiter(value):1808            if func(item):1809                yield item181018111812FILTERS = {1813    "abs": abs,1814    "attr": do_attr,1815    "batch": do_batch,1816    "capitalize": do_capitalize,1817    "center": do_center,1818    "count": len,1819    "d": do_default,1820    "default": do_default,1821    "dictsort": do_dictsort,1822    "e": escape,1823    "escape": escape,1824    "filesizeformat": do_filesizeformat,1825    "first": do_first,1826    "float": do_float,1827    "forceescape": do_forceescape,1828    "format": do_format,1829    "groupby": do_groupby,1830    "indent": do_indent,1831    "int": do_int,1832    "join": do_join,1833    "last": do_last,1834    "length": len,1835    "list": do_list,1836    "lower": do_lower,1837    "items": do_items,1838    "map": do_map,1839    "min": do_min,1840    "max": do_max,1841    "pprint": do_pprint,1842    "random": do_random,1843    "reject": do_reject,1844    "rejectattr": do_rejectattr,1845    "replace": do_replace,1846    "reverse": do_reverse,1847    "round": do_round,1848    "safe": do_mark_safe,1849    "select": do_select,1850    "selectattr": do_selectattr,1851    "slice": do_slice,1852    "sort": do_sort,1853    "string": soft_str,1854    "striptags": do_striptags,1855    "sum": do_sum,1856    "title": do_title,1857    "trim": do_trim,1858    "truncate": do_truncate,1859    "unique": do_unique,1860    "upper": do_upper,1861    "urlencode": do_urlencode,1862    "urlize": do_urlize,1863    "wordcount": do_wordcount,1864    "wordwrap": do_wordwrap,1865    "xmlattr": do_xmlattr,1866    "tojson": do_tojson,1867}