Skip to content
Myr

Merge pull request #1389 from pallets/unify-decorators

Before adoption: this commit came in with the history the project adopted, so no landing records it.

unify/rename context function decorators

authored by David Lord · committed by GitHub · parents 94b381d, 788d8bc · Browse files · 17 files+385 added−241 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+385 added−241 removed

  • tests:+24 added−26 removed
  • other:+361 added−215 removed

17 files+385 added−241 removed

modified:docs/api.rst+46 added-31 removed
589 unmodified lines
590591These helper functions and classes are useful if you add custom filters or592functions to a Jinja environment.593594.. autofunction:: jinja2.environmentfilter594.. autofunction:: jinja2.pass_context595596.. autofunction:: jinja2.pass_eval_context597598.. autofunction:: jinja2.pass_environment599600.. autofunction:: jinja2.contextfilter601602.. autofunction:: jinja2.evalcontextfilter603600.. autofunction:: jinja2.environmentfunction604.. autofunction:: jinja2.environmentfilter605606.. autofunction:: jinja2.contextfunction607608.. autofunction:: jinja2.evalcontextfunction609610.. autofunction:: jinja2.environmentfunction611612.. function:: escape(s)613614 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`615 to HTML-safe sequences. Use this if you need to display text that might
86 unmodified lines
702Some decorators are available to tell Jinja to pass extra information to703the filter. The object is passed as the first argument, making the value704being filtered the second argument.705700- :func:`environmentfilter` passes the :class:`Environment`.701- :func:`evalcontextfilter` passes the :ref:`eval-context`.702- :func:`contextfilter` passes the current706- :func:`pass_environment` passes the :class:`Environment`.707- :func:`pass_eval_context` passes the :ref:`eval-context`.708- :func:`pass_context` passes the current709 :class:`~jinja2.runtime.Context`.710711Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>``712tags. It uses the eval context to check if autoescape is currently
1 unmodified line
714715.. code-block:: python716717 import re712 from jinja2 import evalcontextfilter718 from jinja2 import pass_eval_context719 from markupsafe import Markup, escape720715 @evalcontextfilter721 @pass_eval_context722 def nl2br(eval_ctx, value):723 br = "<br>\n"724725 if eval_ctx.autoescape:
54 unmodified lines
780Some decorators are available to tell Jinja to pass extra information to781the filter. The object is passed as the first argument, making the value782being filtered the second argument.783778- :func:`environmentfunction` passes the :class:`Environment`.779- :func:`evalcontextfunction` passes the :ref:`eval-context`.780- :func:`contextfunction` passes the current784- :func:`pass_environment` passes the :class:`Environment`.785- :func:`pass_eval_context` passes the :ref:`eval-context`.786- :func:`pass_context` passes the current787 :class:`~jinja2.runtime.Context`.788789790.. _eval-context:791792Evaluation Context793------------------794789The evaluation context (short eval context or eval ctx) is a new object790introduced in Jinja 2.4 that makes it possible to activate and deactivate791compiled features at runtime.795The evaluation context (short eval context or eval ctx) makes it796possible to activate and deactivate compiled features at runtime.797793Currently it is only used to enable and disable the automatic escaping but794can be used for extensions as well.798Currently it is only used to enable and disable automatic escaping, but799it can be used by extensions as well.800796In previous Jinja versions filters and functions were marked as797environment callables in order to check for the autoescape status from the798environment. In new versions it's encouraged to check the setting from the799evaluation context instead.801The ``autoescape`` setting should be checked on the evaluation context,802not the environment. The evaluation context will have the computed value803for the current template.804801Previous versions::805Instead of ``pass_environment``:806803 @environmentfilter807.. code-block:: python808809 @pass_environment810 def filter(env, value):811 result = do_something(value)812813 if env.autoescape:814 result = Markup(result)815816 return result817810In new versions you can either use a :func:`contextfilter` and access the811evaluation context from the actual context, or use a812:func:`evalcontextfilter` which directly passes the evaluation context to813the function::818Use ``pass_eval_context`` if you only need the setting:819815 @contextfilter816 def filter(context, value):820.. code-block:: python821822 @pass_eval_context823 def filter(eval_ctx, value):824 result = do_something(value)825818 if context.eval_ctx.autoescape:826 if eval_ctx.autoescape:827 result = Markup(result)828829 return result830822 @evalcontextfilter823 def filter(eval_ctx, value):831Or use ``pass_context`` if you need other context behavior as well:832833.. code-block:: python834835 @pass_context836 def filter(context, value):837 result = do_something(value)838825 if eval_ctx.autoescape:839 if context.eval_ctx.autoescape:840 result = Markup(result)841842 return result843844The evaluation context must not be modified at runtime. Modifications845must only happen with a :class:`nodes.EvalContextModifier` and
104 unmodified lines
modified:docs/faq.rst+6 added-6 removed
111 unmodified lines
112113Why is the Context immutable?114-----------------------------115116When writing a :func:`contextfunction` or something similar you may have117noticed that the context tries to stop you from modifying it. If you have118managed to modify the context by using an internal context API you may119have noticed that changes in the context don't seem to be visible in the120template. The reason for this is that Jinja uses the context only as121primary data source for template variables for performance reasons.116When writing a :func:`pass_context` function, you may have noticed that117the context tries to stop you from modifying it. If you have managed to118modify the context by using an internal context API you may have noticed119that changes in the context don't seem to be visible in the template.120The reason for this is that Jinja uses the context only as primary data121source for template variables for performance reasons.122123If you want to modify the context write a function that returns a variable124instead that one can assign to a variable by using set::125
50 unmodified lines
modified:src/jinja2/__init__.py+3 added
36 unmodified lines
37from .utils import contextfunction38from .utils import environmentfunction39from .utils import evalcontextfunction40from .utils import is_undefined41from .utils import pass_context42from .utils import pass_environment43from .utils import pass_eval_context44from .utils import select_autoescape4546__version__ = "3.0.0a1"
modified:src/jinja2/asyncfilters.py+39 added-27 removed
1import typing2import typing as t3import warnings4from functools import wraps5from itertools import groupby67from . import filters8from .asyncsupport import auto_aiter9from .asyncsupport import auto_await10from .utils import _PassArg11from .utils import pass_eval_context1213if t.TYPE_CHECKING:14 from .environment import Environment15 from .nodes import EvalContext
35 unmodified lines
51 if func(item):52 yield item535452def dualfilter(normal_filter, async_filter):53 wrap_evalctx = False55def dual_filter(normal_func, async_func):56 pass_arg = _PassArg.from_obj(normal_func)57 wrapper_has_eval_context = False5855 if getattr(normal_filter, "environmentfilter", False) is True:59 if pass_arg is _PassArg.environment:60 wrapper_has_eval_context = False6162 def is_async(args):63 return args[0].is_async6460 wrap_evalctx = False65 else:62 has_evalctxfilter = getattr(normal_filter, "evalcontextfilter", False) is True63 has_ctxfilter = getattr(normal_filter, "contextfilter", False) is True64 wrap_evalctx = not has_evalctxfilter and not has_ctxfilter66 wrapper_has_eval_context = pass_arg is None6768 def is_async(args):69 return args[0].environment.is_async7069 @wraps(normal_filter)71 @wraps(normal_func)72 def wrapper(*args, **kwargs):73 b = is_async(args)7473 if wrap_evalctx:75 if wrapper_has_eval_context:76 args = args[1:]7778 if b:77 return async_filter(*args, **kwargs)79 return async_func(*args, **kwargs)8079 return normal_filter(*args, **kwargs)81 return normal_func(*args, **kwargs)8281 if wrap_evalctx:82 wrapper.evalcontextfilter = True83 if wrapper_has_eval_context:84 wrapper = pass_eval_context(wrapper)8584 wrapper.asyncfiltervariant = True86 wrapper.jinja_async_variant = True87 return wrapper888988def asyncfiltervariant(original):90def async_variant(original):91 def decorator(f):90 return dualfilter(original, f)92 return dual_filter(original, f)9394 return decorator959697def asyncfiltervariant(original):98 warnings.warn(99 "'asyncfiltervariant' is renamed to 'async_variant', the old"100 " name will be removed in Jinja 3.1.",101 DeprecationWarning,102 stacklevel=2,103 )104 return async_variant(original)10510695@asyncfiltervariant(filters.do_first)107@async_variant(filters.do_first)108async def do_first(109 environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"110) -> "t.Union[V, Undefined]":111 try:
1 unmodified line
113 except StopAsyncIteration:114 return environment.undefined("No first item, sequence was empty.")115116105@asyncfiltervariant(filters.do_groupby)117@async_variant(filters.do_groupby)118async def do_groupby(119 environment: "Environment",120 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",121 attribute: t.Union[str, int],
5 unmodified lines
127 for key, values in groupby(sorted(await auto_to_seq(value), key=expr), expr)128 ]129130119@asyncfiltervariant(filters.do_join)131@async_variant(filters.do_join)132async def do_join(133 eval_ctx: "EvalContext",134 value: t.Union[t.AsyncIterable, t.Iterable],135 d: str = "",
1 unmodified line
137) -> str:138 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)139140129@asyncfiltervariant(filters.do_list)141@async_variant(filters.do_list)142async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":143 return await auto_to_seq(value)144145134@asyncfiltervariant(filters.do_reject)146@async_variant(filters.do_reject)147async def do_reject(148 context: "Context",149 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",150 *args: t.Any,
1 unmodified line
152) -> "t.AsyncIterator[V]":153 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)154155144@asyncfiltervariant(filters.do_rejectattr)156@async_variant(filters.do_rejectattr)157async def do_rejectattr(158 context: "Context",159 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",160 *args: t.Any,
1 unmodified line
162) -> "t.AsyncIterator[V]":163 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)164165154@asyncfiltervariant(filters.do_select)166@async_variant(filters.do_select)167async def do_select(168 context: "Context",169 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",170 *args: t.Any,
1 unmodified line
172) -> "t.AsyncIterator[V]":173 return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)174175164@asyncfiltervariant(filters.do_selectattr)176@async_variant(filters.do_selectattr)177async def do_selectattr(178 context: "Context",179 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",180 *args: t.Any,
23 unmodified lines
204) -> t.Iterable:205 ...206207196@asyncfiltervariant(filters.do_map)208@async_variant(filters.do_map)209async def do_map(context, value, *args, **kwargs):210 if value:211 func = filters.prepare_map(context, args, kwargs)212213 async for item in auto_aiter(value):214 yield await auto_await(func(item))215216205@asyncfiltervariant(filters.do_sum)217@async_variant(filters.do_sum)218async def do_sum(219 environment: "Environment",220 iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",221 attribute: t.Optional[t.Union[str, int]] = None,
13 unmodified lines
235236 return rv237238227@asyncfiltervariant(filters.do_slice)239@async_variant(filters.do_slice)240async def do_slice(241 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",242 slices: int,243 fill_with: t.Optional[t.Any] = None,
18 unmodified lines
modified:src/jinja2/compiler.py+39 added-41 removed
17 unmodified lines
18from .idtracking import VAR_LOAD_RESOLVE19from .idtracking import VAR_LOAD_UNDEFINED20from .nodes import EvalContext21from .optimizer import Optimizer22from .utils import _PassArg23from .utils import concat24from .visitor import NodeVisitor2526operators = {
950 unmodified lines
977978 if node.ignore_missing:979 self.outdent()980980 def visit_Import(self, node, frame):981 """Visit regular imports."""982 self.writeline(f"{frame.symbols.ref(node.target)} = ", node)983 if frame.toplevel:984 self.write(f"context.vars[{node.target!r}] = ")985981 def _import_common(self, node, frame):982 self.write(f"{self.choose_async('await ')}environment.get_template(")983 self.visit(node.template, frame)984 self.write(f", {self.name!r}).")985986 if node.with_context:987 f_name = f"make_module{self.choose_async('_async')}"988 self.write(989 f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"
1 unmodified line
991 elif self.environment.is_async:992 self.write("_get_default_module_async()")993 else:994 self.write("_get_default_module(context)")995996 def visit_Import(self, node, frame):997 """Visit regular imports."""998 self.writeline(f"{frame.symbols.ref(node.target)} = ", node)999 if frame.toplevel:1000 self.write(f"context.vars[{node.target!r}] = ")10011002 self._import_common(node, frame)10031004 if frame.toplevel and not node.target.startswith("_"):1005 self.writeline(f"context.exported_vars.discard({node.target!r})")10061007 def visit_FromImport(self, node, frame):1008 """Visit named imports."""1009 self.newline(node)1004 prefix = self.choose_async("await ")1005 self.write(f"included_template = {prefix}environment.get_template(")1006 self.visit(node.template, frame)1007 self.write(f", {self.name!r}).")1008 if node.with_context:1009 f_name = f"make_module{self.choose_async('_async')}"1010 self.write(1011 f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"1012 )1013 elif self.environment.is_async:1014 self.write("_get_default_module_async()")1015 else:1016 self.write("_get_default_module(context)")10171010 self.write("included_template = ")1011 self._import_common(node, frame)1012 var_names = []1013 discarded_names = []1014 for name in node.names:1015 if isinstance(name, tuple):
266 unmodified lines
12821283 if self.environment.finalize:1284 src = "environment.finalize("1285 env_finalize = self.environment.finalize1286 pass_arg = {1287 _PassArg.context: "context",1288 _PassArg.eval_context: "context.eval_ctx",1289 _PassArg.environment: "environment",1290 }.get(_PassArg.from_obj(env_finalize))1291 finalize = None12921293 def finalize(value):1294 return default(env_finalize(value))1293 if pass_arg is None:12941296 if getattr(env_finalize, "contextfunction", False) is True:1297 src += "context, "1298 finalize = None # noqa: F8111299 elif getattr(env_finalize, "evalcontextfunction", False) is True:1300 src += "context.eval_ctx, "1301 finalize = None1302 elif getattr(env_finalize, "environmentfunction", False) is True:1303 src += "environment, "13041295 def finalize(value):1306 return default(env_finalize(self.environment, value))1296 return default(env_finalize(value))12971298 else:1299 src = f"{src}{pass_arg}, "13001301 if pass_arg == "environment":13021303 def finalize(value):1304 return default(env_finalize(self.environment, value))13051306 self._finalize = self._FinalizeInfo(finalize, src)1307 return self._finalize13081309 def _output_const_repr(self, group):
360 unmodified lines
1670 def _filter_test_common(self, node, frame, is_filter):1671 if is_filter:1672 compiler_map = self.filters1673 env_map = self.environment.filters1676 type_name = mark_name = "filter"1674 type_name = "filter"1675 else:1676 compiler_map = self.tests1677 env_map = self.environment.tests1678 type_name = "test"1681 # Filters use "contextfilter", tests and calls use "contextfunction".1682 mark_name = "function"16791680 if self.environment.is_async:1681 self.write("await auto_await(")1682
5 unmodified lines
1688 # actually called at runtime. See pull_dependencies.1689 if func is None and not frame.soft_frame:1690 self.fail(f"No {type_name} named {node.name!r}.", node.lineno)16911696 if getattr(func, f"context{mark_name}", False) is True:1697 self.write("context, ")1698 elif getattr(func, f"evalcontext{mark_name}", False) is True:1699 self.write("context.eval_ctx, ")1700 elif getattr(func, f"environment{mark_name}", False) is True:1701 self.write("environment, ")1692 pass_arg = {1693 _PassArg.context: "context",1694 _PassArg.eval_context: "context.eval_ctx",1695 _PassArg.environment: "environment",1696 }.get(_PassArg.from_obj(func))16971698 if pass_arg is not None:1699 self.write(f"{pass_arg}, ")17001701 # Back to the visitor function to handle visiting the target of1702 # the filter or test.1703 yield1704
151 unmodified lines
modified:src/jinja2/environment.py+7 added-7 removed
40 unmodified lines
41from .parser import Parser42from .runtime import Context43from .runtime import new_context44from .runtime import Undefined45from .utils import _PassArg46from .utils import concat47from .utils import consume48from .utils import have_async_gen49from .utils import import_string
414 unmodified lines
464 self, name, value, args, kwargs, context, eval_ctx, is_filter465 ):466 if is_filter:467 env_map = self.filters467 type_name = mark_name = "filter"468 type_name = "filter"469 else:470 env_map = self.tests471 type_name = "test"471 # Filters use "contextfilter", tests and calls use "contextfunction".472 mark_name = "function"472473 func = env_map.get(name)474475 if func is None:
8 unmodified lines
484 raise TemplateRuntimeError(msg)485486 args = [value, *(args if args is not None else ())]487 kwargs = kwargs if kwargs is not None else {}488 pass_arg = _PassArg.from_obj(func)489490 if getattr(func, f"context{mark_name}", False) is True:490 if pass_arg is _PassArg.context:491 if context is None:492 raise TemplateRuntimeError(493 f"Attempted to invoke a context {type_name} without context."494 )495496 args.insert(0, context)497 elif getattr(func, f"evalcontext{mark_name}", False) is True:497 elif pass_arg is _PassArg.eval_context:498 if eval_ctx is None:499 if context is not None:500 eval_ctx = context.eval_ctx501 else:502 eval_ctx = EvalContext(self)503504 args.insert(0, eval_ctx)505 elif getattr(func, f"environment{mark_name}", False) is True:505 elif pass_arg is _PassArg.environment:506 args.insert(0, self)507508 return func(*args, **kwargs)509
21 unmodified lines
531 environment in async mode and the test supports async execution.532 It's your responsibility to await this if needed.533534 .. versionchanged:: 3.0535 Tests support ``@contextfunction``, etc. decorators. Added535 Tests support ``@pass_context``, etc. decorators. Added536 the ``context`` and ``eval_ctx`` parameters.537538 .. versionadded:: 2.7539 """
873 unmodified lines
modified:src/jinja2/ext.py+6 added-6 removed
23 unmodified lines
24from .exceptions import TemplateAssertionError25from .exceptions import TemplateSyntaxError26from .nodes import ContextReference27from .runtime import concat28from .utils import contextfunction28from .utils import import_string29from .utils import pass_context3031# I18N functions available in Jinja templates. If the I18N library32# provides ugettext, it will be assigned to gettext.33GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext", "pgettext", "npgettext")
100 unmodified lines
134 lineno=lineno,135 )136137138@contextfunction138@pass_context139def _gettext_alias(__context, *args, **kwargs):140 return __context.call(__context.resolve("gettext"), *args, **kwargs)141142143def _make_new_gettext(func):144 @contextfunction144 @pass_context145 def gettext(__context, __string, **variables):146 rv = __context.call(func, __string)147 if __context.eval_ctx.autoescape:148 rv = Markup(rv)
5 unmodified lines
154 return gettext155156157def _make_new_ngettext(func):158 @contextfunction158 @pass_context159 def ngettext(__context, __singular, __plural, __num, **variables):160 variables.setdefault("num", __num)161 rv = __context.call(func, __singular, __plural, __num)162 if __context.eval_ctx.autoescape:
4 unmodified lines
167 return ngettext168169170def _make_new_pgettext(func):171 @contextfunction171 @pass_context172 def pgettext(__context, __string_ctx, __string, **variables):173 variables.setdefault("context", __string_ctx)174 rv = __context.call(func, __string_ctx, __string)175
6 unmodified lines
182 return pgettext183184185def _make_new_npgettext(func):186 @contextfunction186 @pass_context187 def npgettext(__context, __string_ctx, __singular, __plural, __num, **variables):188 variables.setdefault("context", __string_ctx)189 variables.setdefault("num", __num)190 rv = __context.call(func, __string_ctx, __singular, __plural, __num)
577 unmodified lines
modified:src/jinja2/filters.py+64 added-39 removed
2 unmodified lines
3import random4import re5import typing6import typing as t7import warnings8from collections import abc9from itertools import chain10from itertools import groupby11
3 unmodified lines
1516from .exceptions import FilterArgumentError17from .runtime import Undefined18from .utils import htmlsafe_json_dumps19from .utils import pass_context20from .utils import pass_environment21from .utils import pass_eval_context22from .utils import pformat23from .utils import url_quote24from .utils import urlize25
5 unmodified lines
31 from .sandbox import SandboxedEnvironment # noqa: F4013233 K = t.TypeVar("K")34 V = t.TypeVar("V")31 F = t.TypeVar("F", bound=t.Callable[..., t.Any])3536 class HasHTML(te.Protocol):37 def __html__(self) -> str:38 pass394038def contextfilter(f: "F") -> "F":39 """Decorator for marking context dependent filters. The current40 :class:`Context` will be passed as first argument.41def contextfilter(f):42 """Pass the context as the first argument to the decorated function.4344 .. deprecated:: 3.0.045 Use :func:`~jinja2.pass_context` instead.46 """42 f.contextfilter = True # type: ignore43 return f47 warnings.warn(48 "'contextfilter' is renamed to 'pass_context', the old name"49 " will be removed in Jinja 3.1.",50 DeprecationWarning,51 stacklevel=2,52 )53 return pass_context(f)545546def evalcontextfilter(f: "F") -> "F":47 """Decorator for marking eval-context dependent filters. An eval48 context object is passed as first argument. For more information49 about the eval context, see :ref:`eval-context`.56def evalcontextfilter(f):57 """Pass the eval context as the first argument to the decorated58 function.5960 .. deprecated:: 3.0.061 Use :func:`~jinja2.pass_eval_context` instead.6263 .. versionadded:: 2.464 """53 f.evalcontextfilter = True # type: ignore54 return f65 warnings.warn(66 "'evalcontextfilter' is renamed to 'pass_eval_context', the old"67 " name will be removed in Jinja 3.1.",68 DeprecationWarning,69 stacklevel=2,70 )71 return pass_eval_context(f)727357def environmentfilter(f: "F") -> "F":58 """Decorator for marking environment dependent filters. The current59 :class:`Environment` is passed to the filter as first argument.74def environmentfilter(f):75 """Pass the environment as the first argument to the decorated76 function.7778 .. deprecated:: 3.0.079 Use :func:`~jinja2.pass_environment` instead.80 """61 f.environmentfilter = True # type: ignore62 return f81 warnings.warn(82 "'environmentfilter' is renamed to 'pass_environment', the old"83 " name will be removed in Jinja 3.1.",84 DeprecationWarning,85 stacklevel=2,86 )87 return pass_environment(f)888990def ignore_case(value: "V") -> "V":91 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings
123 unmodified lines
215 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items216 )217218194@evalcontextfilter219@pass_eval_context220def do_replace(221 eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None222) -> str:223 """Return a copy of the value with all occurrences of a substring
37 unmodified lines
261 """Convert a value to lowercase."""262 return soft_str(s).lower()263264240@evalcontextfilter265@pass_eval_context266def do_xmlattr(267 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True268) -> str:269 """Create an SGML/XML attribute string based on the items in a dict.
96 unmodified lines
366367 return sorted(value.items(), key=sort_func, reverse=reverse)368369345@environmentfilter370@pass_environment371def do_sort(372 environment: "Environment",373 value: "t.Iterable[V]",374 reverse: bool = False,
47 unmodified lines
422 )423 return sorted(value, key=key_func, reverse=reverse)424425401@environmentfilter426@pass_environment427def do_unique(428 environment: "Environment",429 value: "t.Iterable[V]",430 case_sensitive: bool = False,
44 unmodified lines
475 )476 return func(chain([first], it), key=key_func)477478454@environmentfilter479@pass_environment480def do_min(481 environment: "Environment",482 value: "t.Iterable[V]",483 case_sensitive: bool = False,
11 unmodified lines
495 """496 return _min_or_max(environment, value, min, case_sensitive, attribute)497498474@environmentfilter499@pass_environment500def do_max(501 environment: "Environment",502 value: "t.Iterable[V]",503 case_sensitive: bool = False,
44 unmodified lines
548549 return value550551527@evalcontextfilter552@pass_eval_context553def do_join(554 eval_ctx: "EvalContext",555 value: t.Iterable,556 d: str = "",
54 unmodified lines
611 """Centers the value in a field of a given width."""612 return soft_str(value).center(width)613614590@environmentfilter615@pass_environment616def do_first(617 environment: "Environment", seq: "t.Iterable[V]"618) -> "t.Union[V, Undefined]":619 """Return the first item of a sequence."""
2 unmodified lines
622 except StopIteration:623 return environment.undefined("No first item, sequence was empty.")624625601@environmentfilter626@pass_environment627def do_last(628 environment: "Environment", seq: "t.Reversible[V]"629) -> "t.Union[V, Undefined]":630 """Return the last item of a sequence.
10 unmodified lines
641 except StopIteration:642 return environment.undefined("No last item, sequence was empty.")643644620@contextfilter645@pass_context646def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":647 """Return a random item from the sequence."""648 try:649 return random.choice(seq)
41 unmodified lines
691692_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")693694670@evalcontextfilter695@pass_eval_context696def do_urlize(697 eval_ctx: "EvalContext",698 value: str,699 trim_url_limit: t.Optional[int] = None,
119 unmodified lines
819820 return rv821822798@environmentfilter823@pass_environment824def do_truncate(825 env: "Environment",826 s: str,827 length: int = 255,
39 unmodified lines
867 result = s[: length - len(end)].rsplit(" ", 1)[0]868 return result + end869870846@environmentfilter871@pass_environment872def do_wordwrap(873 environment: "Environment",874 s: str,875 width: int = 79,
262 unmodified lines
1138 def __str__(self):1139 return tuple.__str__(self)114011411117@environmentfilter1142@pass_environment1143def do_groupby(1144 environment: "Environment",1145 value: "t.Iterable[V]",1146 attribute: t.Union[str, int],
50 unmodified lines
1197 for key, values in groupby(sorted(value, key=expr), expr)1198 ]119912001176@environmentfilter1201@pass_environment1202def do_sum(1203 environment: "Environment",1204 iterable: "t.Iterable[V]",1205 attribute: t.Optional[t.Union[str, int]] = None,
65 unmodified lines
1271 except TypeError:1272 raise FilterArgumentError("argument must be iterable")127312741250@environmentfilter1275@pass_environment1276def do_attr(1277 environment: "Environment", obj: t.Any, name: str1278) -> t.Union[Undefined, t.Any]:1279 """Get an attribute of an object. ``foo|attr("bar")`` works like
40 unmodified lines
1320) -> t.Iterable:1321 ...132213231299@contextfilter1324@pass_context1325def do_map(context, value, *args, **kwargs):1326 """Applies a filter on a sequence of objects or looks up an attribute.1327 This is useful when dealing with lists of objects but you are really1328 only interested in a certain value of it.
39 unmodified lines
1368 for item in value:1369 yield func(item)137013711347@contextfilter1372@pass_context1373def do_select(1374 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1375) -> "t.Iterator[V]":1376 """Filters a sequence of objects by applying a test to each object,
22 unmodified lines
1399 """1400 return select_or_reject(context, value, args, kwargs, lambda x: x, False)140114021378@contextfilter1403@pass_context1404def do_reject(1405 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1406) -> "t.Iterator[V]":1407 """Filters a sequence of objects by applying a test to each object,
17 unmodified lines
1425 """1426 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)142714281404@contextfilter1429@pass_context1430def do_selectattr(1431 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1432) -> "t.Iterator[V]":1433 """Filters a sequence of objects by applying a test to the specified
21 unmodified lines
1455 """1456 return select_or_reject(context, value, args, kwargs, lambda x: x, True)145714581434@contextfilter1459@pass_context1460def do_rejectattr(1461 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1462) -> "t.Iterator[V]":1463 """Filters a sequence of objects by applying a test to the specified
19 unmodified lines
1483 """1484 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)148514861462@evalcontextfilter1487@pass_eval_context1488def do_tojson(1489 eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None1490) -> Markup:1491 """Serialize an object to a string of JSON, and mark it safe to
157 unmodified lines
modified:src/jinja2/nodes.py+11 added-11 removed
8 unmodified lines
9from typing import Tuple as TupleType1011from markupsafe import Markup1213from .utils import _PassArg1415_binop_to_func = {16 "*": operator.mul,17 "/": operator.truediv,18 "//": operator.floordiv,
628 unmodified lines
647 raise Impossible()648649 if self._is_filter:650 env_map = eval_ctx.environment.filters649 mark_name = "filter"651 else:652 env_map = eval_ctx.environment.tests652 # Filters use "contextfilter", tests and calls use "contextfunction".653 mark_name = "function"653654 func = env_map.get(self.name)655 pass_arg = _PassArg.from_obj(func)656657 if func is None or getattr(func, f"context{mark_name}", False) is True:657 if func is None or pass_arg is _PassArg.context:658 raise Impossible()659660 if eval_ctx.environment.is_async and (661 getattr(func, f"async{mark_name}variant", False)661 getattr(func, "jinja_async_variant", False) is True662 or inspect.iscoroutinefunction(func)663 ):664 raise Impossible()665666 args, kwargs = args_as_const(self, eval_ctx)667 args.insert(0, self.node.as_const(eval_ctx))668669 if getattr(func, f"evalcontext{mark_name}", False) is True:669 if pass_arg is _PassArg.eval_context:670 args.insert(0, eval_ctx)671 elif getattr(func, f"environment{mark_name}", False) is True:671 elif pass_arg is _PassArg.environment:672 args.insert(0, eval_ctx.environment)673674 try:675 return func(*args, **kwargs)
21 unmodified lines
697 the other field are the same as :class:`Call`.698699 .. versionchanged:: 3.0700 ``as_const`` shares the same logic for filters and tests. Tests701 check for volatile, async, and ``@contextfunction`` etc.701 check for volatile, async, and ``@pass_context`` etc.702 decorators.703 """704705 _is_filter = False
283 unmodified lines
989 Assign(Name('foo', ctx='store'),990 Getattr(ContextReference(), 'name'))991992 This is basically equivalent to using the993 :func:`~jinja2.contextfunction` decorator when using the994 high-level API, which causes a reference to the context to be passed995 as the first argument to a function.993 :func:`~jinja2.pass_context` decorator when using the high-level994 API, which causes a reference to the context to be passed as the995 first argument to a function.996 """997998999class DerivedContextReference(Expr):
67 unmodified lines
modified:src/jinja2/runtime.py+16 added-18 removed
11 unmodified lines
12from .exceptions import TemplateNotFound # noqa: F40113from .exceptions import TemplateRuntimeError # noqa: F40114from .exceptions import UndefinedError15from .nodes import EvalContext16from .utils import _PassArg17from .utils import concat17from .utils import evalcontextfunction18from .utils import internalcode19from .utils import missing20from .utils import Namespace # noqa: F40121from .utils import object_type_repr22from .utils import pass_eval_context2324if t.TYPE_CHECKING:25 from .environment import Environment26
144 unmodified lines
171172 The context is immutable. Modifications on :attr:`parent` **must not**173 happen and modifications on :attr:`vars` are allowed from generated174 template code only. Template filters and global functions marked as174 :func:`contextfunction`\\s get the active context passed as first argument175 :func:`pass_context` get the active context passed as first argument176 and are allowed to access the context read-only.177178 The template context supports read only dict operations (`get`,179 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
88 unmodified lines
268 @internalcode269 def call(__self, __obj, *args, **kwargs): # noqa: B902270 """Call the callable with the arguments and keyword arguments271 provided but inject the active context or environment as first271 argument if the callable is a :func:`contextfunction` or272 :func:`environmentfunction`.272 argument if the callable has :func:`pass_context` or273 :func:`pass_environment`.274 """275 if __debug__:276 __traceback_hide__ = True # noqa277278 # Allow callable classes to take a context278 if hasattr(__obj, "__call__"): # noqa: B004279 fn = __obj.__call__280 for fn_type in (281 "contextfunction",282 "evalcontextfunction",283 "environmentfunction",284 ):285 if hasattr(fn, fn_type):286 __obj = fn287 break279 if (280 hasattr(__obj, "__call__") # noqa: B004281 and _PassArg.from_obj(__obj.__call__) is not None282 ):283 __obj = __obj.__call__284285 if callable(__obj):290 if getattr(__obj, "contextfunction", False) is True:286 pass_arg = _PassArg.from_obj(__obj)287288 if pass_arg is _PassArg.context:289 # the active context should have access to variables set in290 # loops and blocks without mutating the context itself291 if kwargs.get("_loop_vars"):292 __self = __self.derived(kwargs["_loop_vars"])293 if kwargs.get("_block_vars"):294 __self = __self.derived(kwargs["_block_vars"])295 args = (__self,) + args298 elif getattr(__obj, "evalcontextfunction", False) is True:296 elif pass_arg is _PassArg.eval_context:297 args = (__self.eval_ctx,) + args300 elif getattr(__obj, "environmentfunction", False) is True:298 elif pass_arg is _PassArg.environment:299 args = (__self.environment,) + args300301 kwargs.pop("_block_vars", None)302 kwargs.pop("_loop_vars", None)
291 unmodified lines
594 default_autoescape = environment.autoescape595 self._default_autoescape = default_autoescape596597 @internalcode600 @evalcontextfunction598 @pass_eval_context599 def __call__(self, *args, **kwargs):600 # This requires a bit of explanation, In the past we used to601 # decide largely based on compile-time information if a macro is602 # safe or unsafe. While there was a volatile mode it was largely
333 unmodified lines
modified:src/jinja2/tests.py+3 added-3 removed
3 unmodified lines
4from collections import abc5from numbers import Number67from .runtime import Undefined8from .utils import environmentfunction8from .utils import pass_environment910if t.TYPE_CHECKING:11 from .environment import Environment12
34 unmodified lines
47 """Like :func:`defined` but the other way round."""48 return isinstance(value, Undefined)495051@environmentfunction51@pass_environment52def test_filter(env: "Environment", value: str) -> bool:53 """Check if a filter exists by name. Useful if a filter may be54 optionally available.55
9 unmodified lines
65 """66 return value in env.filters676869@environmentfunction69@pass_environment70def test_test(env: "Environment", value: str) -> bool:71 """Check if a test exists by name. Useful if a test may be72 optionally available.73
182 unmodified lines
modified:src/jinja2/utils.py+110 added-24 removed
1import enum2import json3import os4import re5import typing as t6import warnings7from collections import abc8from collections import deque9from random import choice10from random import randrange
3 unmodified lines
1415from markupsafe import escape16from markupsafe import Markup1718if t.TYPE_CHECKING:19 F = t.TypeVar("F", bound=t.Callable[..., t.Any])2021# special singleton representing missing values for the runtime22missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()2324# internal code
3 unmodified lines
2829_slash_escape = "\\/" not in json.dumps("/")303127def contextfunction(f):28 """This decorator can be used to mark a function or method context callable.29 A context callable is passed the active :class:`Context` as first argument when30 called from the template. This is useful if a function wants to get access31 to the context or functions provided on the context object. For example32 a function that returns a sorted list of template variables the current33 template exports could look like this::32def pass_context(f: "F") -> "F":33 """Pass the :class:`~jinja2.runtime.Context` as the first argument34 to the decorated function when called while rendering a template.3535 @contextfunction36 def get_exported_names(context):37 return sorted(context.exported_vars)36 Can be used on functions, filters, and tests.3738 If only ``Context.eval_context`` is needed, use39 :func:`pass_eval_context`. If only ``Context.environment`` is40 needed, use :func:`pass_environment`.4142 .. versionadded:: 3.0.043 Replaces ``contextfunction`` and ``contextfilter``.44 """39 f.contextfunction = True45 f.jinja_pass_arg = _PassArg.context # type: ignore46 return f474849def pass_eval_context(f: "F") -> "F":50 """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument51 to the decorated function when called while rendering a template.52 See :ref:`eval-context`.5354 Can be used on functions, filters, and tests.5556 If only ``EvalContext.environment`` is needed, use57 :func:`pass_environment`.5859 .. versionadded:: 3.0.060 Replaces ``evalcontextfunction`` and ``evalcontextfilter``.61 """62 f.jinja_pass_arg = _PassArg.eval_context # type: ignore63 return f646566def pass_environment(f: "F") -> "F":67 """Pass the :class:`~jinja2.Environment` as the first argument to68 the decorated function when called while rendering a template.6970 Can be used on functions, filters, and tests.7172 .. versionadded:: 3.0.073 Replaces ``environmentfunction`` and ``environmentfilter``.74 """75 f.jinja_pass_arg = _PassArg.environment # type: ignore76 return f777879class _PassArg(enum.Enum):80 context = enum.auto()81 eval_context = enum.auto()82 environment = enum.auto()8384 @classmethod85 def from_obj(cls, obj):86 if hasattr(obj, "jinja_pass_arg"):87 return obj.jinja_pass_arg8889 for prefix in "context", "eval_context", "environment":90 squashed = prefix.replace("_", "")9192 for name in f"{squashed}function", f"{squashed}filter":93 if getattr(obj, name, False) is True:94 warnings.warn(95 f"{name!r} is deprecated and will stop working"96 f" in Jinja 3.1. Use 'pass_{prefix}' instead.",97 DeprecationWarning,98 stacklevel=2,99 )100 return cls[prefix]101102103def contextfunction(f):104 """Pass the context as the first argument to the decorated function.105106 .. deprecated:: 3.0.0107 Use :func:`~jinja2.pass_context` instead.108 """109 warnings.warn(110 "'contextfunction' is renamed to 'pass_context', the old name"111 " will be removed in Jinja 3.1.",112 DeprecationWarning,113 stacklevel=2,114 )115 return pass_context(f)116117118def evalcontextfunction(f):44 """This decorator can be used to mark a function or method as an eval45 context callable. This is similar to the :func:`contextfunction`46 but instead of passing the context, an evaluation context object is47 passed. For more information about the eval context, see48 :ref:`eval-context`.119 """Pass the eval context as the first argument to the decorated120 function.121122 .. deprecated:: 3.0.0123 Use :func:`~jinja2.pass_eval_context` instead.124125 .. versionadded:: 2.4126 """52 f.evalcontextfunction = True53 return f127 warnings.warn(128 "'evalcontextfunction' is renamed to 'pass_eval_context', the"129 " old name will be removed in Jinja 3.1.",130 DeprecationWarning,131 stacklevel=2,132 )133 return pass_eval_context(f)134135136def environmentfunction(f):57 """This decorator can be used to mark a function or method as environment58 callable. This decorator works exactly like the :func:`contextfunction`59 decorator just that the first argument is the active :class:`Environment`60 and not context.137 """Pass the environment as the first argument to the decorated138 function.139140 .. deprecated:: 3.0.0141 Use :func:`~jinja2.pass_environment` instead.142 """62 f.environmentfunction = True63 return f143 warnings.warn(144 "'environmentfunction' is renamed to 'pass_environment', the"145 " old name will be removed in Jinja 3.1.",146 DeprecationWarning,147 stacklevel=2,148 )149 return pass_environment(f)150151152def internalcode(f):153 """Marks the function as internally used"""
686 unmodified lines
modified:tests/test_api.py+6 added-6 removed
16 unmodified lines
17from jinja2 import Undefined18from jinja2 import UndefinedError19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import contextfunction21from jinja2.utils import Cycler23from jinja2.utils import environmentfunction24from jinja2.utils import evalcontextfunction22from jinja2.utils import pass_context23from jinja2.utils import pass_environment24from jinja2.utils import pass_eval_context252627class TestExtendedAPI:28 def test_item_and_attribute(self, env):
23 unmodified lines
52 # If template data was finalized, it would print "strintstr".53 assert t.render(value=123) == "<int>"5455 def test_context_finalize(self):56 @contextfunction56 @pass_context57 def finalize(context, value):58 return value * context["scale"]5960 e = Environment(finalize=finalize)61 t = e.from_string("{{ value }}")62 assert t.render(value=5, scale=3) == "15"6364 def test_eval_finalize(self):65 @evalcontextfunction65 @pass_eval_context66 def finalize(eval_ctx, value):67 return str(eval_ctx.autoescape) + value6869 e = Environment(finalize=finalize, autoescape=True)70 t = e.from_string("{{ value }}")71 assert t.render(value="<script>") == "True&lt;script&gt;"7273 def test_env_autoescape(self):74 @environmentfunction74 @pass_environment75 def finalize(env, value):76 return " ".join(77 (env.variable_start_string, repr(value), env.variable_end_string)78 )
356 unmodified lines
modified:tests/test_ext.py+5 added-5 removed
1 unmodified line
2from io import BytesIO34import pytest56from jinja2 import contextfunction6from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import nodes9from jinja2 import pass_context10from jinja2.exceptions import TemplateAssertionError11from jinja2.ext import Extension12from jinja2.lexer import count_newlines13from jinja2.lexer import Token
59 unmodified lines
7374 return value757677@contextfunction77@pass_context78def gettext(context, string):79 language = context.get("LANGUAGE", "en")80 value = languages.get(language, {}).get(string, string)81 return _get_with_context(value)828384@contextfunction84@pass_context85def ngettext(context, s, p, n):86 language = context.get("LANGUAGE", "en")8788 if n != 1:
3 unmodified lines
92 value = languages.get(language, {}).get(s, s)93 return _get_with_context(value)949596@contextfunction96@pass_context97def pgettext(context, c, s):98 language = context.get("LANGUAGE", "en")99 value = languages.get(language, {}).get(s, s)100 return _get_with_context(value, c)101102103@contextfunction103@pass_context104def npgettext(context, c, s, p, n):105 language = context.get("LANGUAGE", "en")106107 if n != 1:
607 unmodified lines
modified:tests/test_regression.py+11 added-13 removed
5 unmodified lines
6from jinja2 import Template7from jinja2 import TemplateAssertionError8from jinja2 import TemplateNotFound9from jinja2 import TemplateSyntaxError10from jinja2.utils import contextfunction10from jinja2.utils import pass_context111213class TestCorner:14 def test_assigned_scoping(self, env):
282 unmodified lines
297 env.get_template("foo/bar.html")298299 assert e.value.name == "foo/bar.html"300301 def test_contextfunction_callable_classes(self, env):302 from jinja2.utils import contextfunction303301 def test_pass_context_callable_class(self, env):302 class CallableClass:305 @contextfunction303 @pass_context304 def __call__(self, ctx):305 return ctx.resolve("hello")306307 tpl = Template("""{{ callableclass() }}""")
322 unmodified lines
630End"""631 )632 assert tmpl.render() == "Start\n1) foo\n2) bar last\nEnd"633636 def test_contextfunction_loop_vars(self, env):637 @contextfunction634 def test_pass_context_loop_vars(self, env):635 @pass_context636 def test(ctx):637 return f"{ctx['i']}{ctx['j']}"638639 tmpl = env.from_string(
10 unmodified lines
650 )651 tmpl.globals["test"] = test652 assert tmpl.render() == "42\n01\n01\n42\n12\n12\n42"653656 def test_contextfunction_scoped_loop_vars(self, env):657 @contextfunction654 def test_pass_context_scoped_loop_vars(self, env):655 @pass_context656 def test(ctx):657 return f"{ctx['i']}"658659 tmpl = env.from_string(
10 unmodified lines
670 )671 tmpl.globals["test"] = test672 assert tmpl.render() == "42\n0\n42\n1\n42"673676 def test_contextfunction_in_blocks(self, env):677 @contextfunction674 def test_pass_context_in_blocks(self, env):675 @pass_context676 def test(ctx):677 return f"{ctx['i']}"678679 tmpl = env.from_string(
8 unmodified lines
688 )689 tmpl.globals["test"] = test690 assert tmpl.render() == "42\n24\n42"691694 def test_contextfunction_block_and_loop(self, env):695 @contextfunction692 def test_pass_context_block_and_loop(self, env):693 @pass_context694 def test(ctx):695 return f"{ctx['i']}"696697 tmpl = env.from_string(
55 unmodified lines
modified:tests/test_runtime.py+2 added-2 removed
54 unmodified lines
55 # it was advanced early, the lists would appear empty.56 assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"575859def test_mock_not_contextfunction():59def test_mock_not_pass_arg_marker():60 """If a callable class has a ``__getattr__`` that returns True-like61 values for arbitrary attrs, it should not be incorrectly identified62 as a ``contextfunction``.62 as a ``pass_context`` function.63 """6465 class Calc:66 def __getattr__(self, item):
9 unmodified lines
modified:CHANGES.rst+11 added-2 removed
42 unmodified lines
43 if-statements and conditional expressions. :issue:`842`44- Add ``is filter`` and ``is test`` tests to test if a name is a45 registered filter or test. This allows checking if a filter is46 available in a template before using it. Test functions can be47 decorated with ``@environmentfunction``, ``@evalcontextfunction``,48 or ``@contextfunction``. :issue:`842`, :pr:`1248`47 decorated with ``@pass_environment``, ``@pass_eval_context``,48 or ``@pass_context``. :issue:`842`, :pr:`1248`49- Support ``pgettext`` and ``npgettext`` (message contexts) in i18n50 extension. :issue:`441`51- The ``|indent`` filter's ``width`` argument can be a string to52 indent by. :pr:`1167`
6 unmodified lines
59- Template rendering only treats ``\n``, ``\r\n`` and ``\r`` as line60 breaks. Other characters are left unchanged. :issue:`769, 952, 1313`61- ``|groupby`` filter takes an optional ``default`` argument.62 :issue:`1359`63- The function and filter decorators have been renamed and unified.64 The old names are deprecated. :issue:`1381`6566 - ``pass_context`` replaces ``contextfunction`` and67 ``contextfilter``.68 - ``pass_eval_context`` replaces ``evalcontextfunction`` and69 ``evalcontextfilter``70 - ``pass_environment`` replaces ``environmentfunction`` and71 ``environmentfilter``.727374Version 2.11.375--------------7677Released 2021-01-31
778 unmodified lines