You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1825 lines
51KB

  1. """Built-in template filters used with the ``|`` operator."""
  2. import math
  3. import random
  4. import re
  5. import typing
  6. import typing as t
  7. import warnings
  8. from collections import abc
  9. from itertools import chain
  10. from itertools import groupby
  11. from markupsafe import escape
  12. from markupsafe import Markup
  13. from markupsafe import soft_str
  14. from .async_utils import async_variant
  15. from .async_utils import auto_aiter
  16. from .async_utils import auto_await
  17. from .async_utils import auto_to_list
  18. from .exceptions import FilterArgumentError
  19. from .runtime import Undefined
  20. from .utils import htmlsafe_json_dumps
  21. from .utils import pass_context
  22. from .utils import pass_environment
  23. from .utils import pass_eval_context
  24. from .utils import pformat
  25. from .utils import url_quote
  26. from .utils import urlize
  27. if t.TYPE_CHECKING:
  28. import typing_extensions as te
  29. from .environment import Environment
  30. from .nodes import EvalContext
  31. from .runtime import Context
  32. from .sandbox import SandboxedEnvironment # noqa: F401
  33. class HasHTML(te.Protocol):
  34. def __html__(self) -> str:
  35. pass
  36. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  37. K = t.TypeVar("K")
  38. V = t.TypeVar("V")
  39. def contextfilter(f: F) -> F:
  40. """Pass the context as the first argument to the decorated function.
  41. .. deprecated:: 3.0
  42. Will be removed in Jinja 3.1. Use :func:`~jinja2.pass_context`
  43. instead.
  44. """
  45. warnings.warn(
  46. "'contextfilter' is renamed to 'pass_context', the old name"
  47. " will be removed in Jinja 3.1.",
  48. DeprecationWarning,
  49. stacklevel=2,
  50. )
  51. return pass_context(f)
  52. def evalcontextfilter(f: F) -> F:
  53. """Pass the eval context as the first argument to the decorated
  54. function.
  55. .. deprecated:: 3.0
  56. Will be removed in Jinja 3.1. Use
  57. :func:`~jinja2.pass_eval_context` instead.
  58. .. versionadded:: 2.4
  59. """
  60. warnings.warn(
  61. "'evalcontextfilter' is renamed to 'pass_eval_context', the old"
  62. " name will be removed in Jinja 3.1.",
  63. DeprecationWarning,
  64. stacklevel=2,
  65. )
  66. return pass_eval_context(f)
  67. def environmentfilter(f: F) -> F:
  68. """Pass the environment as the first argument to the decorated
  69. function.
  70. .. deprecated:: 3.0
  71. Will be removed in Jinja 3.1. Use
  72. :func:`~jinja2.pass_environment` instead.
  73. """
  74. warnings.warn(
  75. "'environmentfilter' is renamed to 'pass_environment', the old"
  76. " name will be removed in Jinja 3.1.",
  77. DeprecationWarning,
  78. stacklevel=2,
  79. )
  80. return pass_environment(f)
  81. def ignore_case(value: V) -> V:
  82. """For use as a postprocessor for :func:`make_attrgetter`. Converts strings
  83. to lowercase and returns other types as-is."""
  84. if isinstance(value, str):
  85. return t.cast(V, value.lower())
  86. return value
  87. def make_attrgetter(
  88. environment: "Environment",
  89. attribute: t.Optional[t.Union[str, int]],
  90. postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  91. default: t.Optional[t.Any] = None,
  92. ) -> t.Callable[[t.Any], t.Any]:
  93. """Returns a callable that looks up the given attribute from a
  94. passed object with the rules of the environment. Dots are allowed
  95. to access attributes of attributes. Integer parts in paths are
  96. looked up as integers.
  97. """
  98. parts = _prepare_attribute_parts(attribute)
  99. def attrgetter(item: t.Any) -> t.Any:
  100. for part in parts:
  101. item = environment.getitem(item, part)
  102. if default is not None and isinstance(item, Undefined):
  103. item = default
  104. if postprocess is not None:
  105. item = postprocess(item)
  106. return item
  107. return attrgetter
  108. def make_multi_attrgetter(
  109. environment: "Environment",
  110. attribute: t.Optional[t.Union[str, int]],
  111. postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
  112. ) -> t.Callable[[t.Any], t.List[t.Any]]:
  113. """Returns a callable that looks up the given comma separated
  114. attributes from a passed object with the rules of the environment.
  115. Dots are allowed to access attributes of each attribute. Integer
  116. parts in paths are looked up as integers.
  117. The value returned by the returned callable is a list of extracted
  118. attribute values.
  119. Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
  120. """
  121. if isinstance(attribute, str):
  122. split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")
  123. else:
  124. split = [attribute]
  125. parts = [_prepare_attribute_parts(item) for item in split]
  126. def attrgetter(item: t.Any) -> t.List[t.Any]:
  127. items = [None] * len(parts)
  128. for i, attribute_part in enumerate(parts):
  129. item_i = item
  130. for part in attribute_part:
  131. item_i = environment.getitem(item_i, part)
  132. if postprocess is not None:
  133. item_i = postprocess(item_i)
  134. items[i] = item_i
  135. return items
  136. return attrgetter
  137. def _prepare_attribute_parts(
  138. attr: t.Optional[t.Union[str, int]]
  139. ) -> t.List[t.Union[str, int]]:
  140. if attr is None:
  141. return []
  142. if isinstance(attr, str):
  143. return [int(x) if x.isdigit() else x for x in attr.split(".")]
  144. return [attr]
  145. def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
  146. """Enforce HTML escaping. This will probably double escape variables."""
  147. if hasattr(value, "__html__"):
  148. value = t.cast("HasHTML", value).__html__()
  149. return escape(str(value))
  150. def do_urlencode(
  151. value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]
  152. ) -> str:
  153. """Quote data for use in a URL path or query using UTF-8.
  154. Basic wrapper around :func:`urllib.parse.quote` when given a
  155. string, or :func:`urllib.parse.urlencode` for a dict or iterable.
  156. :param value: Data to quote. A string will be quoted directly. A
  157. dict or iterable of ``(key, value)`` pairs will be joined as a
  158. query string.
  159. When given a string, "/" is not quoted. HTTP servers treat "/" and
  160. "%2F" equivalently in paths. If you need quoted slashes, use the
  161. ``|replace("/", "%2F")`` filter.
  162. .. versionadded:: 2.7
  163. """
  164. if isinstance(value, str) or not isinstance(value, abc.Iterable):
  165. return url_quote(value)
  166. if isinstance(value, dict):
  167. items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
  168. else:
  169. items = value # type: ignore
  170. return "&".join(
  171. f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
  172. )
  173. @pass_eval_context
  174. def do_replace(
  175. eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
  176. ) -> str:
  177. """Return a copy of the value with all occurrences of a substring
  178. replaced with a new one. The first argument is the substring
  179. that should be replaced, the second is the replacement string.
  180. If the optional third argument ``count`` is given, only the first
  181. ``count`` occurrences are replaced:
  182. .. sourcecode:: jinja
  183. {{ "Hello World"|replace("Hello", "Goodbye") }}
  184. -> Goodbye World
  185. {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
  186. -> d'oh, d'oh, aaargh
  187. """
  188. if count is None:
  189. count = -1
  190. if not eval_ctx.autoescape:
  191. return str(s).replace(str(old), str(new), count)
  192. if (
  193. hasattr(old, "__html__")
  194. or hasattr(new, "__html__")
  195. and not hasattr(s, "__html__")
  196. ):
  197. s = escape(s)
  198. else:
  199. s = soft_str(s)
  200. return s.replace(soft_str(old), soft_str(new), count)
  201. def do_upper(s: str) -> str:
  202. """Convert a value to uppercase."""
  203. return soft_str(s).upper()
  204. def do_lower(s: str) -> str:
  205. """Convert a value to lowercase."""
  206. return soft_str(s).lower()
  207. @pass_eval_context
  208. def do_xmlattr(
  209. eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
  210. ) -> str:
  211. """Create an SGML/XML attribute string based on the items in a dict.
  212. All values that are neither `none` nor `undefined` are automatically
  213. escaped:
  214. .. sourcecode:: html+jinja
  215. <ul{{ {'class': 'my_list', 'missing': none,
  216. 'id': 'list-%d'|format(variable)}|xmlattr }}>
  217. ...
  218. </ul>
  219. Results in something like this:
  220. .. sourcecode:: html
  221. <ul class="my_list" id="list-42">
  222. ...
  223. </ul>
  224. As you can see it automatically prepends a space in front of the item
  225. if the filter returned something unless the second parameter is false.
  226. """
  227. rv = " ".join(
  228. f'{escape(key)}="{escape(value)}"'
  229. for key, value in d.items()
  230. if value is not None and not isinstance(value, Undefined)
  231. )
  232. if autospace and rv:
  233. rv = " " + rv
  234. if eval_ctx.autoescape:
  235. rv = Markup(rv)
  236. return rv
  237. def do_capitalize(s: str) -> str:
  238. """Capitalize a value. The first character will be uppercase, all others
  239. lowercase.
  240. """
  241. return soft_str(s).capitalize()
  242. _word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
  243. def do_title(s: str) -> str:
  244. """Return a titlecased version of the value. I.e. words will start with
  245. uppercase letters, all remaining characters are lowercase.
  246. """
  247. return "".join(
  248. [
  249. item[0].upper() + item[1:].lower()
  250. for item in _word_beginning_split_re.split(soft_str(s))
  251. if item
  252. ]
  253. )
  254. def do_dictsort(
  255. value: t.Mapping[K, V],
  256. case_sensitive: bool = False,
  257. by: 'te.Literal["key", "value"]' = "key",
  258. reverse: bool = False,
  259. ) -> t.List[t.Tuple[K, V]]:
  260. """Sort a dict and yield (key, value) pairs. Python dicts may not
  261. be in the order you want to display them in, so sort them first.
  262. .. sourcecode:: jinja
  263. {% for key, value in mydict|dictsort %}
  264. sort the dict by key, case insensitive
  265. {% for key, value in mydict|dictsort(reverse=true) %}
  266. sort the dict by key, case insensitive, reverse order
  267. {% for key, value in mydict|dictsort(true) %}
  268. sort the dict by key, case sensitive
  269. {% for key, value in mydict|dictsort(false, 'value') %}
  270. sort the dict by value, case insensitive
  271. """
  272. if by == "key":
  273. pos = 0
  274. elif by == "value":
  275. pos = 1
  276. else:
  277. raise FilterArgumentError('You can only sort by either "key" or "value"')
  278. def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:
  279. value = item[pos]
  280. if not case_sensitive:
  281. value = ignore_case(value)
  282. return value
  283. return sorted(value.items(), key=sort_func, reverse=reverse)
  284. @pass_environment
  285. def do_sort(
  286. environment: "Environment",
  287. value: "t.Iterable[V]",
  288. reverse: bool = False,
  289. case_sensitive: bool = False,
  290. attribute: t.Optional[t.Union[str, int]] = None,
  291. ) -> "t.List[V]":
  292. """Sort an iterable using Python's :func:`sorted`.
  293. .. sourcecode:: jinja
  294. {% for city in cities|sort %}
  295. ...
  296. {% endfor %}
  297. :param reverse: Sort descending instead of ascending.
  298. :param case_sensitive: When sorting strings, sort upper and lower
  299. case separately.
  300. :param attribute: When sorting objects or dicts, an attribute or
  301. key to sort by. Can use dot notation like ``"address.city"``.
  302. Can be a list of attributes like ``"age,name"``.
  303. The sort is stable, it does not change the relative order of
  304. elements that compare equal. This makes it is possible to chain
  305. sorts on different attributes and ordering.
  306. .. sourcecode:: jinja
  307. {% for user in users|sort(attribute="name")
  308. |sort(reverse=true, attribute="age") %}
  309. ...
  310. {% endfor %}
  311. As a shortcut to chaining when the direction is the same for all
  312. attributes, pass a comma separate list of attributes.
  313. .. sourcecode:: jinja
  314. {% for user users|sort(attribute="age,name") %}
  315. ...
  316. {% endfor %}
  317. .. versionchanged:: 2.11.0
  318. The ``attribute`` parameter can be a comma separated list of
  319. attributes, e.g. ``"age,name"``.
  320. .. versionchanged:: 2.6
  321. The ``attribute`` parameter was added.
  322. """
  323. key_func = make_multi_attrgetter(
  324. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  325. )
  326. return sorted(value, key=key_func, reverse=reverse)
  327. @pass_environment
  328. def do_unique(
  329. environment: "Environment",
  330. value: "t.Iterable[V]",
  331. case_sensitive: bool = False,
  332. attribute: t.Optional[t.Union[str, int]] = None,
  333. ) -> "t.Iterator[V]":
  334. """Returns a list of unique items from the given iterable.
  335. .. sourcecode:: jinja
  336. {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
  337. -> ['foo', 'bar', 'foobar']
  338. The unique items are yielded in the same order as their first occurrence in
  339. the iterable passed to the filter.
  340. :param case_sensitive: Treat upper and lower case strings as distinct.
  341. :param attribute: Filter objects with unique values for this attribute.
  342. """
  343. getter = make_attrgetter(
  344. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  345. )
  346. seen = set()
  347. for item in value:
  348. key = getter(item)
  349. if key not in seen:
  350. seen.add(key)
  351. yield item
  352. def _min_or_max(
  353. environment: "Environment",
  354. value: "t.Iterable[V]",
  355. func: "t.Callable[..., V]",
  356. case_sensitive: bool,
  357. attribute: t.Optional[t.Union[str, int]],
  358. ) -> "t.Union[V, Undefined]":
  359. it = iter(value)
  360. try:
  361. first = next(it)
  362. except StopIteration:
  363. return environment.undefined("No aggregated item, sequence was empty.")
  364. key_func = make_attrgetter(
  365. environment, attribute, postprocess=ignore_case if not case_sensitive else None
  366. )
  367. return func(chain([first], it), key=key_func)
  368. @pass_environment
  369. def do_min(
  370. environment: "Environment",
  371. value: "t.Iterable[V]",
  372. case_sensitive: bool = False,
  373. attribute: t.Optional[t.Union[str, int]] = None,
  374. ) -> "t.Union[V, Undefined]":
  375. """Return the smallest item from the sequence.
  376. .. sourcecode:: jinja
  377. {{ [1, 2, 3]|min }}
  378. -> 1
  379. :param case_sensitive: Treat upper and lower case strings as distinct.
  380. :param attribute: Get the object with the min value of this attribute.
  381. """
  382. return _min_or_max(environment, value, min, case_sensitive, attribute)
  383. @pass_environment
  384. def do_max(
  385. environment: "Environment",
  386. value: "t.Iterable[V]",
  387. case_sensitive: bool = False,
  388. attribute: t.Optional[t.Union[str, int]] = None,
  389. ) -> "t.Union[V, Undefined]":
  390. """Return the largest item from the sequence.
  391. .. sourcecode:: jinja
  392. {{ [1, 2, 3]|max }}
  393. -> 3
  394. :param case_sensitive: Treat upper and lower case strings as distinct.
  395. :param attribute: Get the object with the max value of this attribute.
  396. """
  397. return _min_or_max(environment, value, max, case_sensitive, attribute)
  398. def do_default(
  399. value: V,
  400. default_value: V = "", # type: ignore
  401. boolean: bool = False,
  402. ) -> V:
  403. """If the value is undefined it will return the passed default value,
  404. otherwise the value of the variable:
  405. .. sourcecode:: jinja
  406. {{ my_variable|default('my_variable is not defined') }}
  407. This will output the value of ``my_variable`` if the variable was
  408. defined, otherwise ``'my_variable is not defined'``. If you want
  409. to use default with variables that evaluate to false you have to
  410. set the second parameter to `true`:
  411. .. sourcecode:: jinja
  412. {{ ''|default('the string was empty', true) }}
  413. .. versionchanged:: 2.11
  414. It's now possible to configure the :class:`~jinja2.Environment` with
  415. :class:`~jinja2.ChainableUndefined` to make the `default` filter work
  416. on nested elements and attributes that may contain undefined values
  417. in the chain without getting an :exc:`~jinja2.UndefinedError`.
  418. """
  419. if isinstance(value, Undefined) or (boolean and not value):
  420. return default_value
  421. return value
  422. @pass_eval_context
  423. def sync_do_join(
  424. eval_ctx: "EvalContext",
  425. value: t.Iterable,
  426. d: str = "",
  427. attribute: t.Optional[t.Union[str, int]] = None,
  428. ) -> str:
  429. """Return a string which is the concatenation of the strings in the
  430. sequence. The separator between elements is an empty string per
  431. default, you can define it with the optional parameter:
  432. .. sourcecode:: jinja
  433. {{ [1, 2, 3]|join('|') }}
  434. -> 1|2|3
  435. {{ [1, 2, 3]|join }}
  436. -> 123
  437. It is also possible to join certain attributes of an object:
  438. .. sourcecode:: jinja
  439. {{ users|join(', ', attribute='username') }}
  440. .. versionadded:: 2.6
  441. The `attribute` parameter was added.
  442. """
  443. if attribute is not None:
  444. value = map(make_attrgetter(eval_ctx.environment, attribute), value)
  445. # no automatic escaping? joining is a lot easier then
  446. if not eval_ctx.autoescape:
  447. return str(d).join(map(str, value))
  448. # if the delimiter doesn't have an html representation we check
  449. # if any of the items has. If yes we do a coercion to Markup
  450. if not hasattr(d, "__html__"):
  451. value = list(value)
  452. do_escape = False
  453. for idx, item in enumerate(value):
  454. if hasattr(item, "__html__"):
  455. do_escape = True
  456. else:
  457. value[idx] = str(item)
  458. if do_escape:
  459. d = escape(d)
  460. else:
  461. d = str(d)
  462. return d.join(value)
  463. # no html involved, to normal joining
  464. return soft_str(d).join(map(soft_str, value))
  465. @async_variant(sync_do_join) # type: ignore
  466. async def do_join(
  467. eval_ctx: "EvalContext",
  468. value: t.Union[t.AsyncIterable, t.Iterable],
  469. d: str = "",
  470. attribute: t.Optional[t.Union[str, int]] = None,
  471. ) -> str:
  472. return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
  473. def do_center(value: str, width: int = 80) -> str:
  474. """Centers the value in a field of a given width."""
  475. return soft_str(value).center(width)
  476. @pass_environment
  477. def sync_do_first(
  478. environment: "Environment", seq: "t.Iterable[V]"
  479. ) -> "t.Union[V, Undefined]":
  480. """Return the first item of a sequence."""
  481. try:
  482. return next(iter(seq))
  483. except StopIteration:
  484. return environment.undefined("No first item, sequence was empty.")
  485. @async_variant(sync_do_first) # type: ignore
  486. async def do_first(
  487. environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
  488. ) -> "t.Union[V, Undefined]":
  489. try:
  490. return await auto_aiter(seq).__anext__()
  491. except StopAsyncIteration:
  492. return environment.undefined("No first item, sequence was empty.")
  493. @pass_environment
  494. def do_last(
  495. environment: "Environment", seq: "t.Reversible[V]"
  496. ) -> "t.Union[V, Undefined]":
  497. """Return the last item of a sequence.
  498. Note: Does not work with generators. You may want to explicitly
  499. convert it to a list:
  500. .. sourcecode:: jinja
  501. {{ data | selectattr('name', '==', 'Jinja') | list | last }}
  502. """
  503. try:
  504. return next(iter(reversed(seq)))
  505. except StopIteration:
  506. return environment.undefined("No last item, sequence was empty.")
  507. # No async do_last, it may not be safe in async mode.
  508. @pass_context
  509. def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
  510. """Return a random item from the sequence."""
  511. try:
  512. return random.choice(seq)
  513. except IndexError:
  514. return context.environment.undefined("No random item, sequence was empty.")
  515. def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:
  516. """Format the value like a 'human-readable' file size (i.e. 13 kB,
  517. 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
  518. Giga, etc.), if the second parameter is set to `True` the binary
  519. prefixes are used (Mebi, Gibi).
  520. """
  521. bytes = float(value)
  522. base = 1024 if binary else 1000
  523. prefixes = [
  524. ("KiB" if binary else "kB"),
  525. ("MiB" if binary else "MB"),
  526. ("GiB" if binary else "GB"),
  527. ("TiB" if binary else "TB"),
  528. ("PiB" if binary else "PB"),
  529. ("EiB" if binary else "EB"),
  530. ("ZiB" if binary else "ZB"),
  531. ("YiB" if binary else "YB"),
  532. ]
  533. if bytes == 1:
  534. return "1 Byte"
  535. elif bytes < base:
  536. return f"{int(bytes)} Bytes"
  537. else:
  538. for i, prefix in enumerate(prefixes):
  539. unit = base ** (i + 2)
  540. if bytes < unit:
  541. return f"{base * bytes / unit:.1f} {prefix}"
  542. return f"{base * bytes / unit:.1f} {prefix}"
  543. def do_pprint(value: t.Any) -> str:
  544. """Pretty print a variable. Useful for debugging."""
  545. return pformat(value)
  546. _uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")
  547. @pass_eval_context
  548. def do_urlize(
  549. eval_ctx: "EvalContext",
  550. value: str,
  551. trim_url_limit: t.Optional[int] = None,
  552. nofollow: bool = False,
  553. target: t.Optional[str] = None,
  554. rel: t.Optional[str] = None,
  555. extra_schemes: t.Optional[t.Iterable[str]] = None,
  556. ) -> str:
  557. """Convert URLs in text into clickable links.
  558. This may not recognize links in some situations. Usually, a more
  559. comprehensive formatter, such as a Markdown library, is a better
  560. choice.
  561. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
  562. addresses. Links with trailing punctuation (periods, commas, closing
  563. parentheses) and leading punctuation (opening parentheses) are
  564. recognized excluding the punctuation. Email addresses that include
  565. header fields are not recognized (for example,
  566. ``mailto:address@example.com?cc=copy@example.com``).
  567. :param value: Original text containing URLs to link.
  568. :param trim_url_limit: Shorten displayed URL values to this length.
  569. :param nofollow: Add the ``rel=nofollow`` attribute to links.
  570. :param target: Add the ``target`` attribute to links.
  571. :param rel: Add the ``rel`` attribute to links.
  572. :param extra_schemes: Recognize URLs that start with these schemes
  573. in addition to the default behavior. Defaults to
  574. ``env.policies["urlize.extra_schemes"]``, which defaults to no
  575. extra schemes.
  576. .. versionchanged:: 3.0
  577. The ``extra_schemes`` parameter was added.
  578. .. versionchanged:: 3.0
  579. Generate ``https://`` links for URLs without a scheme.
  580. .. versionchanged:: 3.0
  581. The parsing rules were updated. Recognize email addresses with
  582. or without the ``mailto:`` scheme. Validate IP addresses. Ignore
  583. parentheses and brackets in more cases.
  584. .. versionchanged:: 2.8
  585. The ``target`` parameter was added.
  586. """
  587. policies = eval_ctx.environment.policies
  588. rel_parts = set((rel or "").split())
  589. if nofollow:
  590. rel_parts.add("nofollow")
  591. rel_parts.update((policies["urlize.rel"] or "").split())
  592. rel = " ".join(sorted(rel_parts)) or None
  593. if target is None:
  594. target = policies["urlize.target"]
  595. if extra_schemes is None:
  596. extra_schemes = policies["urlize.extra_schemes"] or ()
  597. for scheme in extra_schemes:
  598. if _uri_scheme_re.fullmatch(scheme) is None:
  599. raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")
  600. rv = urlize(
  601. value,
  602. trim_url_limit=trim_url_limit,
  603. rel=rel,
  604. target=target,
  605. extra_schemes=extra_schemes,
  606. )
  607. if eval_ctx.autoescape:
  608. rv = Markup(rv)
  609. return rv
  610. def do_indent(
  611. s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
  612. ) -> str:
  613. """Return a copy of the string with each line indented by 4 spaces. The
  614. first line and blank lines are not indented by default.
  615. :param width: Number of spaces, or a string, to indent by.
  616. :param first: Don't skip indenting the first line.
  617. :param blank: Don't skip indenting empty lines.
  618. .. versionchanged:: 3.0
  619. ``width`` can be a string.
  620. .. versionchanged:: 2.10
  621. Blank lines are not indented by default.
  622. Rename the ``indentfirst`` argument to ``first``.
  623. """
  624. if isinstance(width, str):
  625. indention = width
  626. else:
  627. indention = " " * width
  628. newline = "\n"
  629. if isinstance(s, Markup):
  630. indention = Markup(indention)
  631. newline = Markup(newline)
  632. s += newline # this quirk is necessary for splitlines method
  633. if blank:
  634. rv = (newline + indention).join(s.splitlines())
  635. else:
  636. lines = s.splitlines()
  637. rv = lines.pop(0)
  638. if lines:
  639. rv += newline + newline.join(
  640. indention + line if line else line for line in lines
  641. )
  642. if first:
  643. rv = indention + rv
  644. return rv
  645. @pass_environment
  646. def do_truncate(
  647. env: "Environment",
  648. s: str,
  649. length: int = 255,
  650. killwords: bool = False,
  651. end: str = "...",
  652. leeway: t.Optional[int] = None,
  653. ) -> str:
  654. """Return a truncated copy of the string. The length is specified
  655. with the first parameter which defaults to ``255``. If the second
  656. parameter is ``true`` the filter will cut the text at length. Otherwise
  657. it will discard the last word. If the text was in fact
  658. truncated it will append an ellipsis sign (``"..."``). If you want a
  659. different ellipsis sign than ``"..."`` you can specify it using the
  660. third parameter. Strings that only exceed the length by the tolerance
  661. margin given in the fourth parameter will not be truncated.
  662. .. sourcecode:: jinja
  663. {{ "foo bar baz qux"|truncate(9) }}
  664. -> "foo..."
  665. {{ "foo bar baz qux"|truncate(9, True) }}
  666. -> "foo ba..."
  667. {{ "foo bar baz qux"|truncate(11) }}
  668. -> "foo bar baz qux"
  669. {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
  670. -> "foo bar..."
  671. The default leeway on newer Jinja versions is 5 and was 0 before but
  672. can be reconfigured globally.
  673. """
  674. if leeway is None:
  675. leeway = env.policies["truncate.leeway"]
  676. assert length >= len(end), f"expected length >= {len(end)}, got {length}"
  677. assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
  678. if len(s) <= length + leeway:
  679. return s
  680. if killwords:
  681. return s[: length - len(end)] + end
  682. result = s[: length - len(end)].rsplit(" ", 1)[0]
  683. return result + end
  684. @pass_environment
  685. def do_wordwrap(
  686. environment: "Environment",
  687. s: str,
  688. width: int = 79,
  689. break_long_words: bool = True,
  690. wrapstring: t.Optional[str] = None,
  691. break_on_hyphens: bool = True,
  692. ) -> str:
  693. """Wrap a string to the given width. Existing newlines are treated
  694. as paragraphs to be wrapped separately.
  695. :param s: Original text to wrap.
  696. :param width: Maximum length of wrapped lines.
  697. :param break_long_words: If a word is longer than ``width``, break
  698. it across lines.
  699. :param break_on_hyphens: If a word contains hyphens, it may be split
  700. across lines.
  701. :param wrapstring: String to join each wrapped line. Defaults to
  702. :attr:`Environment.newline_sequence`.
  703. .. versionchanged:: 2.11
  704. Existing newlines are treated as paragraphs wrapped separately.
  705. .. versionchanged:: 2.11
  706. Added the ``break_on_hyphens`` parameter.
  707. .. versionchanged:: 2.7
  708. Added the ``wrapstring`` parameter.
  709. """
  710. import textwrap
  711. if wrapstring is None:
  712. wrapstring = environment.newline_sequence
  713. # textwrap.wrap doesn't consider existing newlines when wrapping.
  714. # If the string has a newline before width, wrap will still insert
  715. # a newline at width, resulting in a short line. Instead, split and
  716. # wrap each paragraph individually.
  717. return wrapstring.join(
  718. [
  719. wrapstring.join(
  720. textwrap.wrap(
  721. line,
  722. width=width,
  723. expand_tabs=False,
  724. replace_whitespace=False,
  725. break_long_words=break_long_words,
  726. break_on_hyphens=break_on_hyphens,
  727. )
  728. )
  729. for line in s.splitlines()
  730. ]
  731. )
  732. _word_re = re.compile(r"\w+")
  733. def do_wordcount(s: str) -> int:
  734. """Count the words in that string."""
  735. return len(_word_re.findall(soft_str(s)))
  736. def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
  737. """Convert the value into an integer. If the
  738. conversion doesn't work it will return ``0``. You can
  739. override this default using the first parameter. You
  740. can also override the default base (10) in the second
  741. parameter, which handles input with prefixes such as
  742. 0b, 0o and 0x for bases 2, 8 and 16 respectively.
  743. The base is ignored for decimal numbers and non-string values.
  744. """
  745. try:
  746. if isinstance(value, str):
  747. return int(value, base)
  748. return int(value)
  749. except (TypeError, ValueError):
  750. # this quirk is necessary so that "42.23"|int gives 42.
  751. try:
  752. return int(float(value))
  753. except (TypeError, ValueError):
  754. return default
  755. def do_float(value: t.Any, default: float = 0.0) -> float:
  756. """Convert the value into a floating point number. If the
  757. conversion doesn't work it will return ``0.0``. You can
  758. override this default using the first parameter.
  759. """
  760. try:
  761. return float(value)
  762. except (TypeError, ValueError):
  763. return default
  764. def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
  765. """Apply the given values to a `printf-style`_ format string, like
  766. ``string % values``.
  767. .. sourcecode:: jinja
  768. {{ "%s, %s!"|format(greeting, name) }}
  769. Hello, World!
  770. In most cases it should be more convenient and efficient to use the
  771. ``%`` operator or :meth:`str.format`.
  772. .. code-block:: text
  773. {{ "%s, %s!" % (greeting, name) }}
  774. {{ "{}, {}!".format(greeting, name) }}
  775. .. _printf-style: https://docs.python.org/library/stdtypes.html
  776. #printf-style-string-formatting
  777. """
  778. if args and kwargs:
  779. raise FilterArgumentError(
  780. "can't handle positional and keyword arguments at the same time"
  781. )
  782. return soft_str(value) % (kwargs or args)
  783. def do_trim(value: str, chars: t.Optional[str] = None) -> str:
  784. """Strip leading and trailing characters, by default whitespace."""
  785. return soft_str(value).strip(chars)
  786. def do_striptags(value: "t.Union[str, HasHTML]") -> str:
  787. """Strip SGML/XML tags and replace adjacent whitespace by one space."""
  788. if hasattr(value, "__html__"):
  789. value = t.cast("HasHTML", value).__html__()
  790. return Markup(str(value)).striptags()
  791. def sync_do_slice(
  792. value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None
  793. ) -> "t.Iterator[t.List[V]]":
  794. """Slice an iterator and return a list of lists containing
  795. those items. Useful if you want to create a div containing
  796. three ul tags that represent columns:
  797. .. sourcecode:: html+jinja
  798. <div class="columnwrapper">
  799. {%- for column in items|slice(3) %}
  800. <ul class="column-{{ loop.index }}">
  801. {%- for item in column %}
  802. <li>{{ item }}</li>
  803. {%- endfor %}
  804. </ul>
  805. {%- endfor %}
  806. </div>
  807. If you pass it a second argument it's used to fill missing
  808. values on the last iteration.
  809. """
  810. seq = list(value)
  811. length = len(seq)
  812. items_per_slice = length // slices
  813. slices_with_extra = length % slices
  814. offset = 0
  815. for slice_number in range(slices):
  816. start = offset + slice_number * items_per_slice
  817. if slice_number < slices_with_extra:
  818. offset += 1
  819. end = offset + (slice_number + 1) * items_per_slice
  820. tmp = seq[start:end]
  821. if fill_with is not None and slice_number >= slices_with_extra:
  822. tmp.append(fill_with)
  823. yield tmp
  824. @async_variant(sync_do_slice) # type: ignore
  825. async def do_slice(
  826. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  827. slices: int,
  828. fill_with: t.Optional[t.Any] = None,
  829. ) -> "t.Iterator[t.List[V]]":
  830. return sync_do_slice(await auto_to_list(value), slices, fill_with)
  831. def do_batch(
  832. value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
  833. ) -> "t.Iterator[t.List[V]]":
  834. """
  835. A filter that batches items. It works pretty much like `slice`
  836. just the other way round. It returns a list of lists with the
  837. given number of items. If you provide a second parameter this
  838. is used to fill up missing items. See this example:
  839. .. sourcecode:: html+jinja
  840. <table>
  841. {%- for row in items|batch(3, '&nbsp;') %}
  842. <tr>
  843. {%- for column in row %}
  844. <td>{{ column }}</td>
  845. {%- endfor %}
  846. </tr>
  847. {%- endfor %}
  848. </table>
  849. """
  850. tmp: "t.List[V]" = []
  851. for item in value:
  852. if len(tmp) == linecount:
  853. yield tmp
  854. tmp = []
  855. tmp.append(item)
  856. if tmp:
  857. if fill_with is not None and len(tmp) < linecount:
  858. tmp += [fill_with] * (linecount - len(tmp))
  859. yield tmp
  860. def do_round(
  861. value: float,
  862. precision: int = 0,
  863. method: 'te.Literal["common", "ceil", "floor"]' = "common",
  864. ) -> float:
  865. """Round the number to a given precision. The first
  866. parameter specifies the precision (default is ``0``), the
  867. second the rounding method:
  868. - ``'common'`` rounds either up or down
  869. - ``'ceil'`` always rounds up
  870. - ``'floor'`` always rounds down
  871. If you don't specify a method ``'common'`` is used.
  872. .. sourcecode:: jinja
  873. {{ 42.55|round }}
  874. -> 43.0
  875. {{ 42.55|round(1, 'floor') }}
  876. -> 42.5
  877. Note that even if rounded to 0 precision, a float is returned. If
  878. you need a real integer, pipe it through `int`:
  879. .. sourcecode:: jinja
  880. {{ 42.55|round|int }}
  881. -> 43
  882. """
  883. if method not in {"common", "ceil", "floor"}:
  884. raise FilterArgumentError("method must be common, ceil or floor")
  885. if method == "common":
  886. return round(value, precision)
  887. func = getattr(math, method)
  888. return t.cast(float, func(value * (10 ** precision)) / (10 ** precision))
  889. class _GroupTuple(t.NamedTuple):
  890. grouper: t.Any
  891. list: t.List
  892. # Use the regular tuple repr to hide this subclass if users print
  893. # out the value during debugging.
  894. def __repr__(self) -> str:
  895. return tuple.__repr__(self)
  896. def __str__(self) -> str:
  897. return tuple.__str__(self)
  898. @pass_environment
  899. def sync_do_groupby(
  900. environment: "Environment",
  901. value: "t.Iterable[V]",
  902. attribute: t.Union[str, int],
  903. default: t.Optional[t.Any] = None,
  904. ) -> "t.List[t.Tuple[t.Any, t.List[V]]]":
  905. """Group a sequence of objects by an attribute using Python's
  906. :func:`itertools.groupby`. The attribute can use dot notation for
  907. nested access, like ``"address.city"``. Unlike Python's ``groupby``,
  908. the values are sorted first so only one group is returned for each
  909. unique value.
  910. For example, a list of ``User`` objects with a ``city`` attribute
  911. can be rendered in groups. In this example, ``grouper`` refers to
  912. the ``city`` value of the group.
  913. .. sourcecode:: html+jinja
  914. <ul>{% for city, items in users|groupby("city") %}
  915. <li>{{ city }}
  916. <ul>{% for user in items %}
  917. <li>{{ user.name }}
  918. {% endfor %}</ul>
  919. </li>
  920. {% endfor %}</ul>
  921. ``groupby`` yields namedtuples of ``(grouper, list)``, which
  922. can be used instead of the tuple unpacking above. ``grouper`` is the
  923. value of the attribute, and ``list`` is the items with that value.
  924. .. sourcecode:: html+jinja
  925. <ul>{% for group in users|groupby("city") %}
  926. <li>{{ group.grouper }}: {{ group.list|join(", ") }}
  927. {% endfor %}</ul>
  928. You can specify a ``default`` value to use if an object in the list
  929. does not have the given attribute.
  930. .. sourcecode:: jinja
  931. <ul>{% for city, items in users|groupby("city", default="NY") %}
  932. <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
  933. {% endfor %}</ul>
  934. .. versionchanged:: 3.0
  935. Added the ``default`` parameter.
  936. .. versionchanged:: 2.6
  937. The attribute supports dot notation for nested access.
  938. """
  939. expr = make_attrgetter(environment, attribute, default=default)
  940. return [
  941. _GroupTuple(key, list(values))
  942. for key, values in groupby(sorted(value, key=expr), expr)
  943. ]
  944. @async_variant(sync_do_groupby) # type: ignore
  945. async def do_groupby(
  946. environment: "Environment",
  947. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  948. attribute: t.Union[str, int],
  949. default: t.Optional[t.Any] = None,
  950. ) -> "t.List[t.Tuple[t.Any, t.List[V]]]":
  951. expr = make_attrgetter(environment, attribute, default=default)
  952. return [
  953. _GroupTuple(key, await auto_to_list(values))
  954. for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
  955. ]
  956. @pass_environment
  957. def sync_do_sum(
  958. environment: "Environment",
  959. iterable: "t.Iterable[V]",
  960. attribute: t.Optional[t.Union[str, int]] = None,
  961. start: V = 0, # type: ignore
  962. ) -> V:
  963. """Returns the sum of a sequence of numbers plus the value of parameter
  964. 'start' (which defaults to 0). When the sequence is empty it returns
  965. start.
  966. It is also possible to sum up only certain attributes:
  967. .. sourcecode:: jinja
  968. Total: {{ items|sum(attribute='price') }}
  969. .. versionchanged:: 2.6
  970. The `attribute` parameter was added to allow suming up over
  971. attributes. Also the `start` parameter was moved on to the right.
  972. """
  973. if attribute is not None:
  974. iterable = map(make_attrgetter(environment, attribute), iterable)
  975. return sum(iterable, start)
  976. @async_variant(sync_do_sum) # type: ignore
  977. async def do_sum(
  978. environment: "Environment",
  979. iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  980. attribute: t.Optional[t.Union[str, int]] = None,
  981. start: V = 0, # type: ignore
  982. ) -> V:
  983. rv = start
  984. if attribute is not None:
  985. func = make_attrgetter(environment, attribute)
  986. else:
  987. def func(x: V) -> V:
  988. return x
  989. async for item in auto_aiter(iterable):
  990. rv += func(item)
  991. return rv
  992. def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
  993. """Convert the value into a list. If it was a string the returned list
  994. will be a list of characters.
  995. """
  996. return list(value)
  997. @async_variant(sync_do_list) # type: ignore
  998. async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
  999. return await auto_to_list(value)
  1000. def do_mark_safe(value: str) -> Markup:
  1001. """Mark the value as safe which means that in an environment with automatic
  1002. escaping enabled this variable will not be escaped.
  1003. """
  1004. return Markup(value)
  1005. def do_mark_unsafe(value: str) -> str:
  1006. """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
  1007. return str(value)
  1008. @typing.overload
  1009. def do_reverse(value: str) -> str:
  1010. ...
  1011. @typing.overload
  1012. def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":
  1013. ...
  1014. def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
  1015. """Reverse the object or return an iterator that iterates over it the other
  1016. way round.
  1017. """
  1018. if isinstance(value, str):
  1019. return value[::-1]
  1020. try:
  1021. return reversed(value) # type: ignore
  1022. except TypeError:
  1023. try:
  1024. rv = list(value)
  1025. rv.reverse()
  1026. return rv
  1027. except TypeError:
  1028. raise FilterArgumentError("argument must be iterable")
  1029. @pass_environment
  1030. def do_attr(
  1031. environment: "Environment", obj: t.Any, name: str
  1032. ) -> t.Union[Undefined, t.Any]:
  1033. """Get an attribute of an object. ``foo|attr("bar")`` works like
  1034. ``foo.bar`` just that always an attribute is returned and items are not
  1035. looked up.
  1036. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
  1037. """
  1038. try:
  1039. name = str(name)
  1040. except UnicodeError:
  1041. pass
  1042. else:
  1043. try:
  1044. value = getattr(obj, name)
  1045. except AttributeError:
  1046. pass
  1047. else:
  1048. if environment.sandboxed:
  1049. environment = t.cast("SandboxedEnvironment", environment)
  1050. if not environment.is_safe_attribute(obj, name, value):
  1051. return environment.unsafe_undefined(obj, name)
  1052. return value
  1053. return environment.undefined(obj=obj, name=name)
  1054. @typing.overload
  1055. def sync_do_map(
  1056. context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any
  1057. ) -> t.Iterable:
  1058. ...
  1059. @typing.overload
  1060. def sync_do_map(
  1061. context: "Context",
  1062. value: t.Iterable,
  1063. *,
  1064. attribute: str = ...,
  1065. default: t.Optional[t.Any] = None,
  1066. ) -> t.Iterable:
  1067. ...
  1068. @pass_context
  1069. def sync_do_map(
  1070. context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
  1071. ) -> t.Iterable:
  1072. """Applies a filter on a sequence of objects or looks up an attribute.
  1073. This is useful when dealing with lists of objects but you are really
  1074. only interested in a certain value of it.
  1075. The basic usage is mapping on an attribute. Imagine you have a list
  1076. of users but you are only interested in a list of usernames:
  1077. .. sourcecode:: jinja
  1078. Users on this page: {{ users|map(attribute='username')|join(', ') }}
  1079. You can specify a ``default`` value to use if an object in the list
  1080. does not have the given attribute.
  1081. .. sourcecode:: jinja
  1082. {{ users|map(attribute="username", default="Anonymous")|join(", ") }}
  1083. Alternatively you can let it invoke a filter by passing the name of the
  1084. filter and the arguments afterwards. A good example would be applying a
  1085. text conversion filter on a sequence:
  1086. .. sourcecode:: jinja
  1087. Users on this page: {{ titles|map('lower')|join(', ') }}
  1088. Similar to a generator comprehension such as:
  1089. .. code-block:: python
  1090. (u.username for u in users)
  1091. (getattr(u, "username", "Anonymous") for u in users)
  1092. (do_lower(x) for x in titles)
  1093. .. versionchanged:: 2.11.0
  1094. Added the ``default`` parameter.
  1095. .. versionadded:: 2.7
  1096. """
  1097. if value:
  1098. func = prepare_map(context, args, kwargs)
  1099. for item in value:
  1100. yield func(item)
  1101. @typing.overload
  1102. def do_map(
  1103. context: "Context",
  1104. value: t.Union[t.AsyncIterable, t.Iterable],
  1105. name: str,
  1106. *args: t.Any,
  1107. **kwargs: t.Any,
  1108. ) -> t.Iterable:
  1109. ...
  1110. @typing.overload
  1111. def do_map(
  1112. context: "Context",
  1113. value: t.Union[t.AsyncIterable, t.Iterable],
  1114. *,
  1115. attribute: str = ...,
  1116. default: t.Optional[t.Any] = None,
  1117. ) -> t.Iterable:
  1118. ...
  1119. @async_variant(sync_do_map) # type: ignore
  1120. async def do_map(
  1121. context: "Context",
  1122. value: t.Union[t.AsyncIterable, t.Iterable],
  1123. *args: t.Any,
  1124. **kwargs: t.Any,
  1125. ) -> t.AsyncIterable:
  1126. if value:
  1127. func = prepare_map(context, args, kwargs)
  1128. async for item in auto_aiter(value):
  1129. yield await auto_await(func(item))
  1130. @pass_context
  1131. def sync_do_select(
  1132. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1133. ) -> "t.Iterator[V]":
  1134. """Filters a sequence of objects by applying a test to each object,
  1135. and only selecting the objects with the test succeeding.
  1136. If no test is specified, each object will be evaluated as a boolean.
  1137. Example usage:
  1138. .. sourcecode:: jinja
  1139. {{ numbers|select("odd") }}
  1140. {{ numbers|select("odd") }}
  1141. {{ numbers|select("divisibleby", 3) }}
  1142. {{ numbers|select("lessthan", 42) }}
  1143. {{ strings|select("equalto", "mystring") }}
  1144. Similar to a generator comprehension such as:
  1145. .. code-block:: python
  1146. (n for n in numbers if test_odd(n))
  1147. (n for n in numbers if test_divisibleby(n, 3))
  1148. .. versionadded:: 2.7
  1149. """
  1150. return select_or_reject(context, value, args, kwargs, lambda x: x, False)
  1151. @async_variant(sync_do_select) # type: ignore
  1152. async def do_select(
  1153. context: "Context",
  1154. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1155. *args: t.Any,
  1156. **kwargs: t.Any,
  1157. ) -> "t.AsyncIterator[V]":
  1158. return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
  1159. @pass_context
  1160. def sync_do_reject(
  1161. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1162. ) -> "t.Iterator[V]":
  1163. """Filters a sequence of objects by applying a test to each object,
  1164. and rejecting the objects with the test succeeding.
  1165. If no test is specified, each object will be evaluated as a boolean.
  1166. Example usage:
  1167. .. sourcecode:: jinja
  1168. {{ numbers|reject("odd") }}
  1169. Similar to a generator comprehension such as:
  1170. .. code-block:: python
  1171. (n for n in numbers if not test_odd(n))
  1172. .. versionadded:: 2.7
  1173. """
  1174. return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
  1175. @async_variant(sync_do_reject) # type: ignore
  1176. async def do_reject(
  1177. context: "Context",
  1178. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1179. *args: t.Any,
  1180. **kwargs: t.Any,
  1181. ) -> "t.AsyncIterator[V]":
  1182. return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
  1183. @pass_context
  1184. def sync_do_selectattr(
  1185. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1186. ) -> "t.Iterator[V]":
  1187. """Filters a sequence of objects by applying a test to the specified
  1188. attribute of each object, and only selecting the objects with the
  1189. test succeeding.
  1190. If no test is specified, the attribute's value will be evaluated as
  1191. a boolean.
  1192. Example usage:
  1193. .. sourcecode:: jinja
  1194. {{ users|selectattr("is_active") }}
  1195. {{ users|selectattr("email", "none") }}
  1196. Similar to a generator comprehension such as:
  1197. .. code-block:: python
  1198. (u for user in users if user.is_active)
  1199. (u for user in users if test_none(user.email))
  1200. .. versionadded:: 2.7
  1201. """
  1202. return select_or_reject(context, value, args, kwargs, lambda x: x, True)
  1203. @async_variant(sync_do_selectattr) # type: ignore
  1204. async def do_selectattr(
  1205. context: "Context",
  1206. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1207. *args: t.Any,
  1208. **kwargs: t.Any,
  1209. ) -> "t.AsyncIterator[V]":
  1210. return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
  1211. @pass_context
  1212. def sync_do_rejectattr(
  1213. context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
  1214. ) -> "t.Iterator[V]":
  1215. """Filters a sequence of objects by applying a test to the specified
  1216. attribute of each object, and rejecting the objects with the test
  1217. succeeding.
  1218. If no test is specified, the attribute's value will be evaluated as
  1219. a boolean.
  1220. .. sourcecode:: jinja
  1221. {{ users|rejectattr("is_active") }}
  1222. {{ users|rejectattr("email", "none") }}
  1223. Similar to a generator comprehension such as:
  1224. .. code-block:: python
  1225. (u for user in users if not user.is_active)
  1226. (u for user in users if not test_none(user.email))
  1227. .. versionadded:: 2.7
  1228. """
  1229. return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
  1230. @async_variant(sync_do_rejectattr) # type: ignore
  1231. async def do_rejectattr(
  1232. context: "Context",
  1233. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1234. *args: t.Any,
  1235. **kwargs: t.Any,
  1236. ) -> "t.AsyncIterator[V]":
  1237. return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
  1238. @pass_eval_context
  1239. def do_tojson(
  1240. eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
  1241. ) -> Markup:
  1242. """Serialize an object to a string of JSON, and mark it safe to
  1243. render in HTML. This filter is only for use in HTML documents.
  1244. The returned string is safe to render in HTML documents and
  1245. ``<script>`` tags. The exception is in HTML attributes that are
  1246. double quoted; either use single quotes or the ``|forceescape``
  1247. filter.
  1248. :param value: The object to serialize to JSON.
  1249. :param indent: The ``indent`` parameter passed to ``dumps``, for
  1250. pretty-printing the value.
  1251. .. versionadded:: 2.9
  1252. """
  1253. policies = eval_ctx.environment.policies
  1254. dumps = policies["json.dumps_function"]
  1255. kwargs = policies["json.dumps_kwargs"]
  1256. if indent is not None:
  1257. kwargs = kwargs.copy()
  1258. kwargs["indent"] = indent
  1259. return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
  1260. def prepare_map(
  1261. context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
  1262. ) -> t.Callable[[t.Any], t.Any]:
  1263. if not args and "attribute" in kwargs:
  1264. attribute = kwargs.pop("attribute")
  1265. default = kwargs.pop("default", None)
  1266. if kwargs:
  1267. raise FilterArgumentError(
  1268. f"Unexpected keyword argument {next(iter(kwargs))!r}"
  1269. )
  1270. func = make_attrgetter(context.environment, attribute, default=default)
  1271. else:
  1272. try:
  1273. name = args[0]
  1274. args = args[1:]
  1275. except LookupError:
  1276. raise FilterArgumentError("map requires a filter argument")
  1277. def func(item: t.Any) -> t.Any:
  1278. return context.environment.call_filter(
  1279. name, item, args, kwargs, context=context
  1280. )
  1281. return func
  1282. def prepare_select_or_reject(
  1283. context: "Context",
  1284. args: t.Tuple,
  1285. kwargs: t.Dict[str, t.Any],
  1286. modfunc: t.Callable[[t.Any], t.Any],
  1287. lookup_attr: bool,
  1288. ) -> t.Callable[[t.Any], t.Any]:
  1289. if lookup_attr:
  1290. try:
  1291. attr = args[0]
  1292. except LookupError:
  1293. raise FilterArgumentError("Missing parameter for attribute name")
  1294. transfunc = make_attrgetter(context.environment, attr)
  1295. off = 1
  1296. else:
  1297. off = 0
  1298. def transfunc(x: V) -> V:
  1299. return x
  1300. try:
  1301. name = args[off]
  1302. args = args[1 + off :]
  1303. def func(item: t.Any) -> t.Any:
  1304. return context.environment.call_test(name, item, args, kwargs)
  1305. except LookupError:
  1306. func = bool # type: ignore
  1307. return lambda item: modfunc(func(transfunc(item)))
  1308. def select_or_reject(
  1309. context: "Context",
  1310. value: "t.Iterable[V]",
  1311. args: t.Tuple,
  1312. kwargs: t.Dict[str, t.Any],
  1313. modfunc: t.Callable[[t.Any], t.Any],
  1314. lookup_attr: bool,
  1315. ) -> "t.Iterator[V]":
  1316. if value:
  1317. func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
  1318. for item in value:
  1319. if func(item):
  1320. yield item
  1321. async def async_select_or_reject(
  1322. context: "Context",
  1323. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  1324. args: t.Tuple,
  1325. kwargs: t.Dict[str, t.Any],
  1326. modfunc: t.Callable[[t.Any], t.Any],
  1327. lookup_attr: bool,
  1328. ) -> "t.AsyncIterator[V]":
  1329. if value:
  1330. func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
  1331. async for item in auto_aiter(value):
  1332. if func(item):
  1333. yield item
  1334. FILTERS = {
  1335. "abs": abs,
  1336. "attr": do_attr,
  1337. "batch": do_batch,
  1338. "capitalize": do_capitalize,
  1339. "center": do_center,
  1340. "count": len,
  1341. "d": do_default,
  1342. "default": do_default,
  1343. "dictsort": do_dictsort,
  1344. "e": escape,
  1345. "escape": escape,
  1346. "filesizeformat": do_filesizeformat,
  1347. "first": do_first,
  1348. "float": do_float,
  1349. "forceescape": do_forceescape,
  1350. "format": do_format,
  1351. "groupby": do_groupby,
  1352. "indent": do_indent,
  1353. "int": do_int,
  1354. "join": do_join,
  1355. "last": do_last,
  1356. "length": len,
  1357. "list": do_list,
  1358. "lower": do_lower,
  1359. "map": do_map,
  1360. "min": do_min,
  1361. "max": do_max,
  1362. "pprint": do_pprint,
  1363. "random": do_random,
  1364. "reject": do_reject,
  1365. "rejectattr": do_rejectattr,
  1366. "replace": do_replace,
  1367. "reverse": do_reverse,
  1368. "round": do_round,
  1369. "safe": do_mark_safe,
  1370. "select": do_select,
  1371. "selectattr": do_selectattr,
  1372. "slice": do_slice,
  1373. "sort": do_sort,
  1374. "string": soft_str,
  1375. "striptags": do_striptags,
  1376. "sum": do_sum,
  1377. "title": do_title,
  1378. "trim": do_trim,
  1379. "truncate": do_truncate,
  1380. "unique": do_unique,
  1381. "upper": do_upper,
  1382. "urlencode": do_urlencode,
  1383. "urlize": do_urlize,
  1384. "wordcount": do_wordcount,
  1385. "wordwrap": do_wordwrap,
  1386. "xmlattr": do_xmlattr,
  1387. "tojson": do_tojson,
  1388. }