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
Provenance
- Commit
39846a8- Tree
9441ab5- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
94b381d- Parent 2
788d8bc
17 files changed+385 added−241 removed
modified:docs/api.rst+46 added-31 removed
589 unmodified lines590 591 These helper functions and classes are useful if you add custom filters or592 functions to a Jinja environment.593 594-.. autofunction:: jinja2.environmentfilter594+.. autofunction:: jinja2.pass_context595 596+.. autofunction:: jinja2.pass_eval_context597+598+.. autofunction:: jinja2.pass_environment599+600 .. autofunction:: jinja2.contextfilter601 602 .. autofunction:: jinja2.evalcontextfilter603 600-.. autofunction:: jinja2.environmentfunction604+.. autofunction:: jinja2.environmentfilter605 606 .. autofunction:: jinja2.contextfunction607 608 .. autofunction:: jinja2.evalcontextfunction609 610+.. autofunction:: jinja2.environmentfunction611+612 .. function:: escape(s)613 614 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`615 to HTML-safe sequences. Use this if you need to display text that might86 unmodified lines702 Some decorators are available to tell Jinja to pass extra information to703 the filter. The object is passed as the first argument, making the value704 being filtered the second argument.705 700-- :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`.710 711 Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>``712 tags. It uses the eval context to check if autoescape is currently1 unmodified line714 715 .. code-block:: python716 717 import re712- from jinja2 import evalcontextfilter718+ from jinja2 import pass_eval_context719 from markupsafe import Markup, escape720 715- @evalcontextfilter721+ @pass_eval_context722 def nl2br(eval_ctx, value):723 br = "<br>\n"724 725 if eval_ctx.autoescape:54 unmodified lines780 Some decorators are available to tell Jinja to pass extra information to781 the filter. The object is passed as the first argument, making the value782 being filtered the second argument.783 778-- :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`.788 789 790 .. _eval-context:791 792 Evaluation Context793 ------------------794 789-The evaluation context (short eval context or eval ctx) is a new object790-introduced in Jinja 2.4 that makes it possible to activate and deactivate791-compiled features at runtime.795+The evaluation context (short eval context or eval ctx) makes it796+possible to activate and deactivate compiled features at runtime.797 793-Currently it is only used to enable and disable the automatic escaping but794-can be used for extensions as well.798+Currently it is only used to enable and disable automatic escaping, but799+it can be used by extensions as well.800 796-In previous Jinja versions filters and functions were marked as797-environment callables in order to check for the autoescape status from the798-environment. In new versions it's encouraged to check the setting from the799-evaluation context instead.801+The ``autoescape`` setting should be checked on the evaluation context,802+not the environment. The evaluation context will have the computed value803+for the current template.804 801-Previous versions::805+Instead of ``pass_environment``:806 803- @environmentfilter807+.. code-block:: python808+809+ @pass_environment810 def filter(env, value):811 result = do_something(value)812+813 if env.autoescape:814 result = Markup(result)815+816 return result817 810-In new versions you can either use a :func:`contextfilter` and access the811-evaluation context from the actual context, or use a812-:func:`evalcontextfilter` which directly passes the evaluation context to813-the function::818+Use ``pass_eval_context`` if you only need the setting:819 815- @contextfilter816- def filter(context, value):820+.. code-block:: python821+822+ @pass_eval_context823+ def filter(eval_ctx, value):824 result = do_something(value)825+818- if context.eval_ctx.autoescape:826+ if eval_ctx.autoescape:827 result = Markup(result)828+829 return result830 822- @evalcontextfilter823- def filter(eval_ctx, value):831+Or use ``pass_context`` if you need other context behavior as well:832+833+.. code-block:: python834+835+ @pass_context836+ def filter(context, value):837 result = do_something(value)838+825- if eval_ctx.autoescape:839+ if context.eval_ctx.autoescape:840 result = Markup(result)841+842 return result843 844 The evaluation context must not be modified at runtime. Modifications845 must only happen with a :class:`nodes.EvalContextModifier` and104 unmodified linesmodified:docs/faq.rst+6 added-6 removed
111 unmodified lines112 113 Why is the Context immutable?114 -----------------------------115 116-When writing a :func:`contextfunction` or something similar you may have117-noticed that the context tries to stop you from modifying it. If you have118-managed to modify the context by using an internal context API you may119-have noticed that changes in the context don't seem to be visible in the120-template. The reason for this is that Jinja uses the context only as121-primary data source for template variables for performance reasons.116+When writing a :func:`pass_context` function, you may have noticed that117+the context tries to stop you from modifying it. If you have managed to118+modify the context by using an internal context API you may have noticed119+that changes in the context don't seem to be visible in the template.120+The reason for this is that Jinja uses the context only as primary data121+source for template variables for performance reasons.122 123 If you want to modify the context write a function that returns a variable124 instead that one can assign to a variable by using set::125 50 unmodified linesmodified:src/jinja2/__init__.py+3 added
36 unmodified lines37 from .utils import contextfunction38 from .utils import environmentfunction39 from .utils import evalcontextfunction40 from .utils import is_undefined41+from .utils import pass_context42+from .utils import pass_environment43+from .utils import pass_eval_context44 from .utils import select_autoescape45 46 __version__ = "3.0.0a1"modified:src/jinja2/asyncfilters.py+39 added-27 removed
1 import typing2 import typing as t3+import warnings4 from functools import wraps5 from itertools import groupby6 7 from . import filters8 from .asyncsupport import auto_aiter9 from .asyncsupport import auto_await10+from .utils import _PassArg11+from .utils import pass_eval_context12 13 if t.TYPE_CHECKING:14 from .environment import Environment15 from .nodes import EvalContext35 unmodified lines51 if func(item):52 yield item53 54 52-def dualfilter(normal_filter, async_filter):53- wrap_evalctx = False55+def dual_filter(normal_func, async_func):56+ pass_arg = _PassArg.from_obj(normal_func)57+ wrapper_has_eval_context = False58 55- if getattr(normal_filter, "environmentfilter", False) is True:59+ if pass_arg is _PassArg.environment:60+ wrapper_has_eval_context = False61 62 def is_async(args):63 return args[0].is_async64 60- 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 None67 68 def is_async(args):69 return args[0].environment.is_async70 69- @wraps(normal_filter)71+ @wraps(normal_func)72 def wrapper(*args, **kwargs):73 b = is_async(args)74 73- if wrap_evalctx:75+ if wrapper_has_eval_context:76 args = args[1:]77 78 if b:77- return async_filter(*args, **kwargs)79+ return async_func(*args, **kwargs)80 79- return normal_filter(*args, **kwargs)81+ return normal_func(*args, **kwargs)82 81- if wrap_evalctx:82- wrapper.evalcontextfilter = True83+ if wrapper_has_eval_context:84+ wrapper = pass_eval_context(wrapper)85 84- wrapper.asyncfiltervariant = True86+ wrapper.jinja_async_variant = True87 return wrapper88 89 88-def asyncfiltervariant(original):90+def async_variant(original):91 def decorator(f):90- return dualfilter(original, f)92+ return dual_filter(original, f)93 94 return decorator95 96 97+def 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)105+106+95-@asyncfiltervariant(filters.do_first)107+@async_variant(filters.do_first)108 async def do_first(109 environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"110 ) -> "t.Union[V, Undefined]":111 try:1 unmodified line113 except StopAsyncIteration:114 return environment.undefined("No first item, sequence was empty.")115 116 105-@asyncfiltervariant(filters.do_groupby)117+@async_variant(filters.do_groupby)118 async def do_groupby(119 environment: "Environment",120 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",121 attribute: t.Union[str, int],5 unmodified lines127 for key, values in groupby(sorted(await auto_to_seq(value), key=expr), expr)128 ]129 130 119-@asyncfiltervariant(filters.do_join)131+@async_variant(filters.do_join)132 async def do_join(133 eval_ctx: "EvalContext",134 value: t.Union[t.AsyncIterable, t.Iterable],135 d: str = "",1 unmodified line137 ) -> str:138 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)139 140 129-@asyncfiltervariant(filters.do_list)141+@async_variant(filters.do_list)142 async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":143 return await auto_to_seq(value)144 145 134-@asyncfiltervariant(filters.do_reject)146+@async_variant(filters.do_reject)147 async def do_reject(148 context: "Context",149 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",150 *args: t.Any,1 unmodified line152 ) -> "t.AsyncIterator[V]":153 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)154 155 144-@asyncfiltervariant(filters.do_rejectattr)156+@async_variant(filters.do_rejectattr)157 async def do_rejectattr(158 context: "Context",159 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",160 *args: t.Any,1 unmodified line162 ) -> "t.AsyncIterator[V]":163 return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)164 165 154-@asyncfiltervariant(filters.do_select)166+@async_variant(filters.do_select)167 async def do_select(168 context: "Context",169 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",170 *args: t.Any,1 unmodified line172 ) -> "t.AsyncIterator[V]":173 return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)174 175 164-@asyncfiltervariant(filters.do_selectattr)176+@async_variant(filters.do_selectattr)177 async def do_selectattr(178 context: "Context",179 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",180 *args: t.Any,23 unmodified lines204 ) -> t.Iterable:205 ...206 207 196-@asyncfiltervariant(filters.do_map)208+@async_variant(filters.do_map)209 async def do_map(context, value, *args, **kwargs):210 if value:211 func = filters.prepare_map(context, args, kwargs)212 213 async for item in auto_aiter(value):214 yield await auto_await(func(item))215 216 205-@asyncfiltervariant(filters.do_sum)217+@async_variant(filters.do_sum)218 async 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 lines235 236 return rv237 238 227-@asyncfiltervariant(filters.do_slice)239+@async_variant(filters.do_slice)240 async 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 linesmodified:src/jinja2/compiler.py+39 added-41 removed
17 unmodified lines18 from .idtracking import VAR_LOAD_RESOLVE19 from .idtracking import VAR_LOAD_UNDEFINED20 from .nodes import EvalContext21 from .optimizer import Optimizer22+from .utils import _PassArg23 from .utils import concat24 from .visitor import NodeVisitor25 26 operators = {950 unmodified lines977 978 if node.ignore_missing:979 self.outdent()980 980- 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}] = ")985-981+ 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}).")985+986 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 line991 elif self.environment.is_async:992 self.write("_get_default_module_async()")993 else:994 self.write("_get_default_module(context)")995+996+ 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}] = ")1001+1002+ self._import_common(node, frame)1003+1004 if frame.toplevel and not node.target.startswith("_"):1005 self.writeline(f"context.exported_vars.discard({node.target!r})")1006 1007 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)")1017-1010+ 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 lines1282 1283 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 = None1292 1293- def finalize(value):1294- return default(env_finalize(value))1293+ if pass_arg is None:1294 1296- 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, "1304-1295 def finalize(value):1306- return default(env_finalize(self.environment, value))1296+ return default(env_finalize(value))1297 1298+ else:1299+ src = f"{src}{pass_arg}, "1300+1301+ if pass_arg == "environment":1302+1303+ def finalize(value):1304+ return default(env_finalize(self.environment, value))1305+1306 self._finalize = self._FinalizeInfo(finalize, src)1307 return self._finalize1308 1309 def _output_const_repr(self, group):360 unmodified lines1670 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"1679 1680 if self.environment.is_async:1681 self.write("await auto_await(")1682 5 unmodified lines1688 # 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)1691 1696- 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))1697 1698+ if pass_arg is not None:1699+ self.write(f"{pass_arg}, ")1700+1701 # Back to the visitor function to handle visiting the target of1702 # the filter or test.1703 yield1704 151 unmodified linesmodified:src/jinja2/environment.py+7 added-7 removed
40 unmodified lines41 from .parser import Parser42 from .runtime import Context43 from .runtime import new_context44 from .runtime import Undefined45+from .utils import _PassArg46 from .utils import concat47 from .utils import consume48 from .utils import have_async_gen49 from .utils import import_string414 unmodified lines464 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"472 473 func = env_map.get(name)474 475 if func is None:8 unmodified lines484 raise TemplateRuntimeError(msg)485 486 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)489 490- 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 )495 496 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)503 504 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)507 508 return func(*args, **kwargs)509 21 unmodified lines531 environment in async mode and the test supports async execution.532 It's your responsibility to await this if needed.533 534 .. versionchanged:: 3.0535- Tests support ``@contextfunction``, etc. decorators. Added535+ Tests support ``@pass_context``, etc. decorators. Added536 the ``context`` and ``eval_ctx`` parameters.537 538 .. versionadded:: 2.7539 """873 unmodified linesmodified:src/jinja2/ext.py+6 added-6 removed
23 unmodified lines24 from .exceptions import TemplateAssertionError25 from .exceptions import TemplateSyntaxError26 from .nodes import ContextReference27 from .runtime import concat28-from .utils import contextfunction28 from .utils import import_string29+from .utils import pass_context30 31 # I18N functions available in Jinja templates. If the I18N library32 # provides ugettext, it will be assigned to gettext.33 GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext", "pgettext", "npgettext")100 unmodified lines134 lineno=lineno,135 )136 137 138-@contextfunction138+@pass_context139 def _gettext_alias(__context, *args, **kwargs):140 return __context.call(__context.resolve("gettext"), *args, **kwargs)141 142 143 def _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 lines154 return gettext155 156 157 def _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 lines167 return ngettext168 169 170 def _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 lines182 return pgettext183 184 185 def _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 linesmodified:src/jinja2/filters.py+64 added-39 removed
2 unmodified lines3 import random4 import re5 import typing6 import typing as t7+import warnings8 from collections import abc9 from itertools import chain10 from itertools import groupby11 3 unmodified lines15 16 from .exceptions import FilterArgumentError17 from .runtime import Undefined18 from .utils import htmlsafe_json_dumps19+from .utils import pass_context20+from .utils import pass_environment21+from .utils import pass_eval_context22 from .utils import pformat23 from .utils import url_quote24 from .utils import urlize25 5 unmodified lines31 from .sandbox import SandboxedEnvironment # noqa: F40132 33 K = t.TypeVar("K")34 V = t.TypeVar("V")31- F = t.TypeVar("F", bound=t.Callable[..., t.Any])35 36 class HasHTML(te.Protocol):37 def __html__(self) -> str:38 pass39 40 38-def contextfilter(f: "F") -> "F":39- """Decorator for marking context dependent filters. The current40- :class:`Context` will be passed as first argument.41+def contextfilter(f):42+ """Pass the context as the first argument to the decorated function.43+44+ .. 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)54 55 46-def 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`.56+def evalcontextfilter(f):57+ """Pass the eval context as the first argument to the decorated58+ function.59 60+ .. deprecated:: 3.0.061+ Use :func:`~jinja2.pass_eval_context` instead.62+63 .. 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)72 73 57-def environmentfilter(f: "F") -> "F":58- """Decorator for marking environment dependent filters. The current59- :class:`Environment` is passed to the filter as first argument.74+def environmentfilter(f):75+ """Pass the environment as the first argument to the decorated76+ function.77+78+ .. 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)88 89 90 def ignore_case(value: "V") -> "V":91 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings123 unmodified lines215 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items216 )217 218 194-@evalcontextfilter219+@pass_eval_context220 def 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 substring37 unmodified lines261 """Convert a value to lowercase."""262 return soft_str(s).lower()263 264 240-@evalcontextfilter265+@pass_eval_context266 def 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 lines366 367 return sorted(value.items(), key=sort_func, reverse=reverse)368 369 345-@environmentfilter370+@pass_environment371 def do_sort(372 environment: "Environment",373 value: "t.Iterable[V]",374 reverse: bool = False,47 unmodified lines422 )423 return sorted(value, key=key_func, reverse=reverse)424 425 401-@environmentfilter426+@pass_environment427 def do_unique(428 environment: "Environment",429 value: "t.Iterable[V]",430 case_sensitive: bool = False,44 unmodified lines475 )476 return func(chain([first], it), key=key_func)477 478 454-@environmentfilter479+@pass_environment480 def do_min(481 environment: "Environment",482 value: "t.Iterable[V]",483 case_sensitive: bool = False,11 unmodified lines495 """496 return _min_or_max(environment, value, min, case_sensitive, attribute)497 498 474-@environmentfilter499+@pass_environment500 def do_max(501 environment: "Environment",502 value: "t.Iterable[V]",503 case_sensitive: bool = False,44 unmodified lines548 549 return value550 551 527-@evalcontextfilter552+@pass_eval_context553 def do_join(554 eval_ctx: "EvalContext",555 value: t.Iterable,556 d: str = "",54 unmodified lines611 """Centers the value in a field of a given width."""612 return soft_str(value).center(width)613 614 590-@environmentfilter615+@pass_environment616 def do_first(617 environment: "Environment", seq: "t.Iterable[V]"618 ) -> "t.Union[V, Undefined]":619 """Return the first item of a sequence."""2 unmodified lines622 except StopIteration:623 return environment.undefined("No first item, sequence was empty.")624 625 601-@environmentfilter626+@pass_environment627 def do_last(628 environment: "Environment", seq: "t.Reversible[V]"629 ) -> "t.Union[V, Undefined]":630 """Return the last item of a sequence.10 unmodified lines641 except StopIteration:642 return environment.undefined("No last item, sequence was empty.")643 644 620-@contextfilter645+@pass_context646 def 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 lines691 692 _uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")693 694 670-@evalcontextfilter695+@pass_eval_context696 def do_urlize(697 eval_ctx: "EvalContext",698 value: str,699 trim_url_limit: t.Optional[int] = None,119 unmodified lines819 820 return rv821 822 798-@environmentfilter823+@pass_environment824 def do_truncate(825 env: "Environment",826 s: str,827 length: int = 255,39 unmodified lines867 result = s[: length - len(end)].rsplit(" ", 1)[0]868 return result + end869 870 846-@environmentfilter871+@pass_environment872 def do_wordwrap(873 environment: "Environment",874 s: str,875 width: int = 79,262 unmodified lines1138 def __str__(self):1139 return tuple.__str__(self)1140 1141 1117-@environmentfilter1142+@pass_environment1143 def do_groupby(1144 environment: "Environment",1145 value: "t.Iterable[V]",1146 attribute: t.Union[str, int],50 unmodified lines1197 for key, values in groupby(sorted(value, key=expr), expr)1198 ]1199 1200 1176-@environmentfilter1201+@pass_environment1202 def do_sum(1203 environment: "Environment",1204 iterable: "t.Iterable[V]",1205 attribute: t.Optional[t.Union[str, int]] = None,65 unmodified lines1271 except TypeError:1272 raise FilterArgumentError("argument must be iterable")1273 1274 1250-@environmentfilter1275+@pass_environment1276 def 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 like40 unmodified lines1320 ) -> t.Iterable:1321 ...1322 1323 1299-@contextfilter1324+@pass_context1325 def 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 lines1368 for item in value:1369 yield func(item)1370 1371 1347-@contextfilter1372+@pass_context1373 def 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 lines1399 """1400 return select_or_reject(context, value, args, kwargs, lambda x: x, False)1401 1402 1378-@contextfilter1403+@pass_context1404 def 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 lines1425 """1426 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)1427 1428 1404-@contextfilter1429+@pass_context1430 def 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 specified21 unmodified lines1455 """1456 return select_or_reject(context, value, args, kwargs, lambda x: x, True)1457 1458 1434-@contextfilter1459+@pass_context1460 def 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 specified19 unmodified lines1483 """1484 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)1485 1486 1462-@evalcontextfilter1487+@pass_eval_context1488 def 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 to157 unmodified linesmodified:src/jinja2/nodes.py+11 added-11 removed
8 unmodified lines9 from typing import Tuple as TupleType10 11 from markupsafe import Markup12 13+from .utils import _PassArg14+15 _binop_to_func = {16 "*": operator.mul,17 "/": operator.truediv,18 "//": operator.floordiv,628 unmodified lines647 raise Impossible()648 649 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"653 654 func = env_map.get(self.name)655+ pass_arg = _PassArg.from_obj(func)656 657- 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()659 660 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()665 666 args, kwargs = args_as_const(self, eval_ctx)667 args.insert(0, self.node.as_const(eval_ctx))668 669- 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)673 674 try:675 return func(*args, **kwargs)21 unmodified lines697 the other field are the same as :class:`Call`.698 699 .. 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 """704 705 _is_filter = False283 unmodified lines989 Assign(Name('foo', ctx='store'),990 Getattr(ContextReference(), 'name'))991 992 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 """997 998 999 class DerivedContextReference(Expr):67 unmodified linesmodified:src/jinja2/runtime.py+16 added-18 removed
11 unmodified lines12 from .exceptions import TemplateNotFound # noqa: F40113 from .exceptions import TemplateRuntimeError # noqa: F40114 from .exceptions import UndefinedError15 from .nodes import EvalContext16+from .utils import _PassArg17 from .utils import concat17-from .utils import evalcontextfunction18 from .utils import internalcode19 from .utils import missing20 from .utils import Namespace # noqa: F40121 from .utils import object_type_repr22+from .utils import pass_eval_context23 24 if t.TYPE_CHECKING:25 from .environment import Environment26 144 unmodified lines171 172 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.177 178 The template context supports read only dict operations (`get`,179 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,88 unmodified lines268 @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 # noqa277 278 # 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__284 285 if callable(__obj):290- if getattr(__obj, "contextfunction", False) is True:286+ pass_arg = _PassArg.from_obj(__obj)287+288+ 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,) + args300 301 kwargs.pop("_block_vars", None)302 kwargs.pop("_loop_vars", None)291 unmodified lines594 default_autoescape = environment.autoescape595 self._default_autoescape = default_autoescape596 597 @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 largely333 unmodified linesmodified:src/jinja2/tests.py+3 added-3 removed
3 unmodified lines4 from collections import abc5 from numbers import Number6 7 from .runtime import Undefined8-from .utils import environmentfunction8+from .utils import pass_environment9 10 if t.TYPE_CHECKING:11 from .environment import Environment12 34 unmodified lines47 """Like :func:`defined` but the other way round."""48 return isinstance(value, Undefined)49 50 51-@environmentfunction51+@pass_environment52 def 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 lines65 """66 return value in env.filters67 68 69-@environmentfunction69+@pass_environment70 def 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 linesmodified:src/jinja2/utils.py+110 added-24 removed
1+import enum2 import json3 import os4 import re5 import typing as t6+import warnings7 from collections import abc8 from collections import deque9 from random import choice10 from random import randrange3 unmodified lines14 15 from markupsafe import escape16 from markupsafe import Markup17 18+if t.TYPE_CHECKING:19+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])20+21 # special singleton representing missing values for the runtime22 missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()23 24 # internal code3 unmodified lines28 29 _slash_escape = "\\/" not in json.dumps("/")30 31 27-def 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::32+def 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.35 35- @contextfunction36- def get_exported_names(context):37- return sorted(context.exported_vars)36+ Can be used on functions, filters, and tests.37+38+ If only ``Context.eval_context`` is needed, use39+ :func:`pass_eval_context`. If only ``Context.environment`` is40+ needed, use :func:`pass_environment`.41+42+ .. versionadded:: 3.0.043+ Replaces ``contextfunction`` and ``contextfilter``.44 """39- f.contextfunction = True45+ f.jinja_pass_arg = _PassArg.context # type: ignore46 return f47 48 49+def 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`.53+54+ Can be used on functions, filters, and tests.55+56+ If only ``EvalContext.environment`` is needed, use57+ :func:`pass_environment`.58+59+ .. versionadded:: 3.0.060+ Replaces ``evalcontextfunction`` and ``evalcontextfilter``.61+ """62+ f.jinja_pass_arg = _PassArg.eval_context # type: ignore63+ return f64+65+66+def 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.69+70+ Can be used on functions, filters, and tests.71+72+ .. versionadded:: 3.0.073+ Replaces ``environmentfunction`` and ``environmentfilter``.74+ """75+ f.jinja_pass_arg = _PassArg.environment # type: ignore76+ return f77+78+79+class _PassArg(enum.Enum):80+ context = enum.auto()81+ eval_context = enum.auto()82+ environment = enum.auto()83+84+ @classmethod85+ def from_obj(cls, obj):86+ if hasattr(obj, "jinja_pass_arg"):87+ return obj.jinja_pass_arg88+89+ for prefix in "context", "eval_context", "environment":90+ squashed = prefix.replace("_", "")91+92+ 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]101+102+103+def contextfunction(f):104+ """Pass the context as the first argument to the decorated function.105+106+ .. 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)116+117+118 def 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.121 122+ .. deprecated:: 3.0.0123+ Use :func:`~jinja2.pass_eval_context` instead.124+125 .. 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)134 135 136 def 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.139+140+ .. 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)150 151 152 def internalcode(f):153 """Marks the function as internally used"""686 unmodified linesmodified:tests/test_api.py+6 added-6 removed
16 unmodified lines17 from jinja2 import Undefined18 from jinja2 import UndefinedError19 from jinja2.compiler import CodeGenerator20 from jinja2.runtime import Context21-from jinja2.utils import contextfunction21 from jinja2.utils import Cycler23-from jinja2.utils import environmentfunction24-from jinja2.utils import evalcontextfunction22+from jinja2.utils import pass_context23+from jinja2.utils import pass_environment24+from jinja2.utils import pass_eval_context25 26 27 class TestExtendedAPI:28 def test_item_and_attribute(self, env):23 unmodified lines52 # If template data was finalized, it would print "strintstr".53 assert t.render(value=123) == "<int>"54 55 def test_context_finalize(self):56- @contextfunction56+ @pass_context57 def finalize(context, value):58 return value * context["scale"]59 60 e = Environment(finalize=finalize)61 t = e.from_string("{{ value }}")62 assert t.render(value=5, scale=3) == "15"63 64 def test_eval_finalize(self):65- @evalcontextfunction65+ @pass_eval_context66 def finalize(eval_ctx, value):67 return str(eval_ctx.autoescape) + value68 69 e = Environment(finalize=finalize, autoescape=True)70 t = e.from_string("{{ value }}")71 assert t.render(value="<script>") == "True<script>"72 73 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 linesmodified:tests/test_ext.py+5 added-5 removed
1 unmodified line2 from io import BytesIO3 4 import pytest5 6-from jinja2 import contextfunction6 from jinja2 import DictLoader7 from jinja2 import Environment8 from jinja2 import nodes9+from jinja2 import pass_context10 from jinja2.exceptions import TemplateAssertionError11 from jinja2.ext import Extension12 from jinja2.lexer import count_newlines13 from jinja2.lexer import Token59 unmodified lines73 74 return value75 76 77-@contextfunction77+@pass_context78 def gettext(context, string):79 language = context.get("LANGUAGE", "en")80 value = languages.get(language, {}).get(string, string)81 return _get_with_context(value)82 83 84-@contextfunction84+@pass_context85 def ngettext(context, s, p, n):86 language = context.get("LANGUAGE", "en")87 88 if n != 1:3 unmodified lines92 value = languages.get(language, {}).get(s, s)93 return _get_with_context(value)94 95 96-@contextfunction96+@pass_context97 def 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)101 102 103-@contextfunction103+@pass_context104 def npgettext(context, c, s, p, n):105 language = context.get("LANGUAGE", "en")106 107 if n != 1:607 unmodified linesmodified:tests/test_regression.py+11 added-13 removed
5 unmodified lines6 from jinja2 import Template7 from jinja2 import TemplateAssertionError8 from jinja2 import TemplateNotFound9 from jinja2 import TemplateSyntaxError10-from jinja2.utils import contextfunction10+from jinja2.utils import pass_context11 12 13 class TestCorner:14 def test_assigned_scoping(self, env):282 unmodified lines297 env.get_template("foo/bar.html")298 299 assert e.value.name == "foo/bar.html"300 301- def test_contextfunction_callable_classes(self, env):302- from jinja2.utils import contextfunction303-301+ def test_pass_context_callable_class(self, env):302 class CallableClass:305- @contextfunction303+ @pass_context304 def __call__(self, ctx):305 return ctx.resolve("hello")306 307 tpl = Template("""{{ callableclass() }}""")322 unmodified lines630 End"""631 )632 assert tmpl.render() == "Start\n1) foo\n2) bar last\nEnd"633 636- 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']}"638 639 tmpl = env.from_string(10 unmodified lines650 )651 tmpl.globals["test"] = test652 assert tmpl.render() == "42\n01\n01\n42\n12\n12\n42"653 656- 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']}"658 659 tmpl = env.from_string(10 unmodified lines670 )671 tmpl.globals["test"] = test672 assert tmpl.render() == "42\n0\n42\n1\n42"673 676- 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']}"678 679 tmpl = env.from_string(8 unmodified lines688 )689 tmpl.globals["test"] = test690 assert tmpl.render() == "42\n24\n42"691 694- 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']}"696 697 tmpl = env.from_string(55 unmodified linesmodified:tests/test_runtime.py+2 added-2 removed
54 unmodified lines55 # it was advanced early, the lists would appear empty.56 assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"57 58 59-def test_mock_not_contextfunction():59+def 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 """64 65 class Calc:66 def __getattr__(self, item):9 unmodified linesmodified:CHANGES.rst+11 added-2 removed
42 unmodified lines43 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 lines59 - 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`65 66+ - ``pass_context`` replaces ``contextfunction`` and67+ ``contextfilter``.68+ - ``pass_eval_context`` replaces ``evalcontextfunction`` and69+ ``evalcontextfilter``70+ - ``pass_environment`` replaces ``environmentfunction`` and71+ ``environmentfilter``.72 73+74 Version 2.11.375 --------------76 77 Released 2021-01-31778 unmodified lines