rewrite docs, clean up typing for template decorators
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent daf1510 · Browse files · 3 files·+227 added−178 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+227 added−178 removed
- other:+227 added−178 removed
Provenance
- Commit
edebd37- Tree
f054466- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
daf1510
3 files changed+227 added−178 removed
modified:docs/templating.rst+42 added-20 removed
135 unmodified lines136 using in this block.137 138 .. _registering-filters:139 140-Registering Filters141--------------------140+Registering Filters, Tests, and Globals141+---------------------------------------142 143-If you want to register your own filters in Jinja2 you have two ways to do144-that. You can either put them by hand into the145-:attr:`~flask.Flask.jinja_env` of the application or use the146-:meth:`~flask.Flask.template_filter` decorator.143+The Flask app and blueprints provide decorators and methods to register your own144+filters, tests, and global functions for use in Jinja templates. They all follow145+the same pattern, so the following examples only discuss filters.146 148-The following examples work the same and all reverse an object::147+Decorate a function with :meth:`~.Flask.template_filter` to register it as a148+template filter.149 150- @app.template_filter # use the function name as filter name151- def reverse_filter(s):152- return s[::-1]150+.. code-block:: python151 154- @app.template_filter('reverse')152+ @app.template_filter153+ def reverse(s):154+ return reversed(s)155+156+.. code-block:: jinja157+158+ {% for item in data | reverse %}159+ {% endfor %}160+161+By default it will use the name of the function as the name of the filter, but162+that can be changed by passing a name to the decorator.163+164+.. code-block:: python165+166+ @app.template_filter("reverse")167 def reverse_filter(s):156- return s[::-1]168+ return reversed(s)169 170+A filter can be registered separately using :meth:`~.Flask.add_template_filter`.171+The name is optional and will use the function name if not given.172+173+.. code-block:: python174+175 def reverse_filter(s):159- return s[::-1]160- app.jinja_env.filters['reverse'] = reverse_filter176+ return reversed(s)177 162-In case of the decorator the argument is optional if you want to use the163-function name as name of the filter. Once registered, you can use the filter164-in your templates in the same way as Jinja2's builtin filters, for example if165-you have a Python list in context called `mylist`::178+ app.add_template_filter(reverse_filter, "reverse")179 167- {% for x in mylist | reverse %}168- {% endfor %}180+For template tests, use the :meth:`~.Flask.template_test` decorator or181+:meth:`~.Flask.add_template_test` method. For template global functions, use the182+:meth:`~.Flask.template_global` decorator or :meth:`~.Flask.add_template_global`183+method.184 185+The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to186+indicate that the registered functions will be avaialble to all templates, not187+only when rendering from within the blueprint.188 189+The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be190+modified directly, as you would when using Jinja outside Flask.191+192+193 Context Processors194 ------------------195 196 To inject new variables automatically into the context of a template,59 unmodified linesmodified:src/flask/sansio/app.py+82 added-86 removed
658 unmodified lines659 f" endpoint function: {endpoint}"660 )661 self.view_functions[endpoint] = view_func662 663+ @t.overload664+ def template_filter(self, name: T_template_filter) -> T_template_filter: ...665+ @t.overload666+ def template_filter(667+ self, name: str | None = None668+ ) -> t.Callable[[T_template_filter], T_template_filter]: ...669 @setupmethod670 def template_filter(665- self, name: t.Callable[..., t.Any] | str | None = None666- ) -> t.Callable[[T_template_filter], T_template_filter] | T_template_filter:667- """A decorator that is used to register custom template filter.668- You can specify a name for the filter, otherwise the function669- name will be used. Example::671+ self, name: T_template_filter | str | None = None672+ ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:673+ """Decorate a function to register it as a custom Jinja filter. The name674+ is optional. The decorator may be used without parentheses.675 671- @app.template_filter()672- def reverse(s):673- return s[::-1]676+ .. code-block:: python677 675- The decorator also can be used without parentheses::678+ @app.template_filter("reverse")679+ def reverse_filter(s):680+ return reversed(s)681 677- @app.template_filter678- def reverse(s):679- return s[::-1]682+ The :meth:`add_template_filter` method may be used to register a683+ function later rather than decorating.684 681- :param name: the optional name of the filter, otherwise the682- function name will be used.685+ :param name: The name to register the filter as. If not given, uses the686+ function's name.687 """684-688 if callable(name):686- # If name is callable, it is the function to register.687- # This is a shortcut for the common case of688- # @app.template_filter689- # def func():689+ self.add_template_filter(name)690+ return name691 691- func = name692- self.add_template_filter(func)693- return func694-692 def decorator(f: T_template_filter) -> T_template_filter:693 self.add_template_filter(f, name=name)694 return f695 2 unmodified lines698 @setupmethod699 def add_template_filter(700 self, f: ft.TemplateFilterCallable, name: str | None = None701 ) -> None:705- """Register a custom template filter. Works exactly like the706- :meth:`template_filter` decorator.702+ """Register a function to use as a custom Jinja filter.703 708- :param name: the optional name of the filter, otherwise the709- function name will be used.704+ The :meth:`template_filter` decorator can be used to register a function705+ by decorating instead.706+707+ :param f: The function to register.708+ :param name: The name to register the filter as. If not given, uses the709+ function's name.710 """711 self.jinja_env.filters[name or f.__name__] = f712 713+ @t.overload714+ def template_test(self, name: T_template_test) -> T_template_test: ...715+ @t.overload716+ def template_test(717+ self, name: str | None = None718+ ) -> t.Callable[[T_template_test], T_template_test]: ...719 @setupmethod720 def template_test(715- self, name: t.Callable[..., t.Any] | str | None = None716- ) -> t.Callable[[T_template_test], T_template_test] | T_template_filter:717- """A decorator that is used to register custom template test.718- You can specify a name for the test, otherwise the function719- name will be used. Example::721+ self, name: T_template_test | str | None = None722+ ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:723+ """Decorate a function to register it as a custom Jinja test. The name724+ is optional. The decorator may be used without parentheses.725 726+ .. code-block:: python727+721- @app.template_test()722- def is_prime(n):728+ @app.template_test("prime")729+ def is_prime_test(n):730 if n == 2:731 return True732 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):733 if n % i == 0:734 return False735 return True736 730- The decorator also can be used without parentheses::737+ The :meth:`add_template_test` method may be used to register a function738+ later rather than decorating.739 732- @app.template_test733- def is_prime(n):734- if n == 2:735- return True736- for i in range(2, int(math.ceil(math.sqrt(n))) + 1):737- if n % i == 0:738- return False740+ :param name: The name to register the filter as. If not given, uses the741+ function's name.742 743 .. versionadded:: 0.10741-742- :param name: the optional name of the test, otherwise the743- function name will be used.744 """745-745 if callable(name):747- # If name is callable, it is the function to register.748- # This is a shortcut for the common case of749- # @app.template_test750- # def func():746+ self.add_template_test(name)747+ return name # type: ignore[return-value]748 752- func = name753- self.add_template_test(func)754- return func755-749 def decorator(f: T_template_test) -> T_template_test:750 self.add_template_test(f, name=name)751 return f752 2 unmodified lines755 @setupmethod756 def add_template_test(757 self, f: ft.TemplateTestCallable, name: str | None = None758 ) -> None:766- """Register a custom template test. Works exactly like the767- :meth:`template_test` decorator.759+ """Register a function to use as a custom Jinja test.760 769- .. versionadded:: 0.10761+ The :meth:`template_test` decorator can be used to register a function762+ by decorating instead.763 771- :param name: the optional name of the test, otherwise the772- function name will be used.764+ :param f: The function to register.765+ :param name: The name to register the test as. If not given, uses the766+ function's name.767+768+ .. versionadded:: 0.10769 """770 self.jinja_env.tests[name or f.__name__] = f771 772+ @t.overload773+ def template_global(self, name: T_template_global) -> T_template_global: ...774+ @t.overload775+ def template_global(776+ self, name: str | None = None777+ ) -> t.Callable[[T_template_global], T_template_global]: ...778 @setupmethod779 def template_global(778- self, name: t.Callable[..., t.Any] | str | None = None779- ) -> t.Callable[[T_template_global], T_template_global] | T_template_filter:780- """A decorator that is used to register a custom template global function.781- You can specify a name for the global function, otherwise the function782- name will be used. Example::780+ self, name: T_template_global | str | None = None781+ ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:782+ """Decorate a function to register it as a custom Jinja global. The name783+ is optional. The decorator may be used without parentheses.784 784- @app.template_global()785- def double(n):786- return 2 * n785+ .. code-block:: python786 788- The decorator also can be used without parentheses::789-787 @app.template_global788 def double(n):789 return 2 * n790 794- .. versionadded:: 0.10791+ The :meth:`add_template_global` method may be used to register a792+ function later rather than decorating.793 796- :param name: the optional name of the global function, otherwise the797- function name will be used.798- """794+ :param name: The name to register the global as. If not given, uses the795+ function's name.796 797+ .. versionadded:: 0.10798+ """799 if callable(name):801- # If name is callable, it is the function to register.802- # This is a shortcut for the common case of803- # @app.template_global804- # def func():800+ self.add_template_global(name)801+ return name802 806- func = name807- self.add_template_global(func)808- return func809-803 def decorator(f: T_template_global) -> T_template_global:804 self.add_template_global(f, name=name)805 return f806 2 unmodified lines809 @setupmethod810 def add_template_global(811 self, f: ft.TemplateGlobalCallable, name: str | None = None812 ) -> None:820- """Register a custom template global function. Works exactly like the821- :meth:`template_global` decorator.813+ """Register a function to use as a custom Jinja global.814 823- .. versionadded:: 0.10815+ The :meth:`template_global` decorator can be used to register a function816+ by decorating instead.817 825- :param name: the optional name of the global function, otherwise the826- function name will be used.818+ :param f: The function to register.819+ :param name: The name to register the global as. If not given, uses the820+ function's name.821+822+ .. versionadded:: 0.10823 """824 self.jinja_env.globals[name or f.__name__] = f825 826 @setupmethod186 unmodified linesmodified:src/flask/sansio/blueprints.py+103 added-72 removed
438 unmodified lines439 **options,440 )441 )442 443+ @t.overload444+ def app_template_filter(self, name: T_template_filter) -> T_template_filter: ...445+ @t.overload446+ def app_template_filter(447+ self, name: str | None = None448+ ) -> t.Callable[[T_template_filter], T_template_filter]: ...449 @setupmethod450 def app_template_filter(445- self, name: t.Callable[..., t.Any] | str | None = None446- ) -> t.Callable[[T_template_filter], T_template_filter] | T_template_filter:447- """Register a template filter, available in any template rendered by the448- application. Equivalent to :meth:`.Flask.template_filter`.451+ self, name: T_template_filter | str | None = None452+ ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]:453+ """Decorate a function to register it as a custom Jinja filter. The name454+ is optional. The decorator may be used without parentheses.455 450- :param name: the optional name of the filter, otherwise the451- function name will be used.452- """456+ The :meth:`add_app_template_filter` method may be used to register a457+ function later rather than decorating.458 459+ The filter is available in all templates, not only those under this460+ blueprint. Equivalent to :meth:`.Flask.template_filter`.461+462+ :param name: The name to register the filter as. If not given, uses the463+ function's name.464+ """465 if callable(name):455- # If name is callable, it is the function to register.456- # This is a shortcut for the common case of457- # @bp.add_template_filter458- # def func():466+ self.add_app_template_filter(name)467+ return name468 460- func = name461- self.add_app_template_filter(func)462- return func463-469 def decorator(f: T_template_filter) -> T_template_filter:470 self.add_app_template_filter(f, name=name)471 return f472 2 unmodified lines475 @setupmethod476 def add_app_template_filter(477 self, f: ft.TemplateFilterCallable, name: str | None = None478 ) -> None:474- """Register a template filter, available in any template rendered by the475- application. Works like the :meth:`app_template_filter` decorator. Equivalent to476- :meth:`.Flask.add_template_filter`.479+ """Register a function to use as a custom Jinja filter.480 478- :param name: the optional name of the filter, otherwise the479- function name will be used.481+ The :meth:`app_template_filter` decorator can be used to register a482+ function by decorating instead.483+484+ The filter is available in all templates, not only those under this485+ blueprint. Equivalent to :meth:`.Flask.add_template_filter`.486+487+ :param f: The function to register.488+ :param name: The name to register the filter as. If not given, uses the489+ function's name.490 """491 482- def register_template(state: BlueprintSetupState) -> None:483- state.app.jinja_env.filters[name or f.__name__] = f492+ def register_template_filter(state: BlueprintSetupState) -> None:493+ state.app.add_template_filter(f, name=name)494 485- self.record_once(register_template)495+ self.record_once(register_template_filter)496 497+ @t.overload498+ def app_template_test(self, name: T_template_test) -> T_template_test: ...499+ @t.overload500+ def app_template_test(501+ self, name: str | None = None502+ ) -> t.Callable[[T_template_test], T_template_test]: ...503 @setupmethod504 def app_template_test(489- self, name: t.Callable[..., t.Any] | str | None = None490- ) -> t.Callable[[T_template_test], T_template_test] | T_template_filter:491- """Register a template test, available in any template rendered by the492- application. Equivalent to :meth:`.Flask.template_test`.505+ self, name: T_template_test | str | None = None506+ ) -> T_template_test | t.Callable[[T_template_test], T_template_test]:507+ """Decorate a function to register it as a custom Jinja test. The name508+ is optional. The decorator may be used without parentheses.509 494- .. versionadded:: 0.10510+ The :meth:`add_app_template_test` method may be used to register a511+ function later rather than decorating.512 496- :param name: the optional name of the test, otherwise the497- function name will be used.498- """513+ The test is available in all templates, not only those under this514+ blueprint. Equivalent to :meth:`.Flask.template_test`.515 516+ :param name: The name to register the filter as. If not given, uses the517+ function's name.518+519+ .. versionadded:: 0.10520+ """521 if callable(name):501- # If name is callable, it is the function to register.502- # This is a shortcut for the common case of503- # @bp.add_template_test504- # def func():522+ self.add_app_template_test(name)523+ return name # type: ignore[return-value]524 506- func = name507- self.add_app_template_test(func)508- return func509-525 def decorator(f: T_template_test) -> T_template_test:526 self.add_app_template_test(f, name=name)527 return f528 2 unmodified lines531 @setupmethod532 def add_app_template_test(533 self, f: ft.TemplateTestCallable, name: str | None = None534 ) -> None:520- """Register a template test, available in any template rendered by the521- application. Works like the :meth:`app_template_test` decorator. Equivalent to522- :meth:`.Flask.add_template_test`.535+ """Register a function to use as a custom Jinja test.536 524- .. versionadded:: 0.10537+ The :meth:`app_template_test` decorator can be used to register a538+ function by decorating instead.539 526- :param name: the optional name of the test, otherwise the527- function name will be used.540+ The test is available in all templates, not only those under this541+ blueprint. Equivalent to :meth:`.Flask.add_template_test`.542+543+ :param f: The function to register.544+ :param name: The name to register the test as. If not given, uses the545+ function's name.546+547+ .. versionadded:: 0.10548 """549 530- def register_template(state: BlueprintSetupState) -> None:531- state.app.jinja_env.tests[name or f.__name__] = f550+ def register_template_test(state: BlueprintSetupState) -> None:551+ state.app.add_template_test(f, name=name)552 533- self.record_once(register_template)553+ self.record_once(register_template_test)554 555+ @t.overload556+ def app_template_global(self, name: T_template_global) -> T_template_global: ...557+ @t.overload558+ def app_template_global(559+ self, name: str | None = None560+ ) -> t.Callable[[T_template_global], T_template_global]: ...561 @setupmethod562 def app_template_global(537- self, name: t.Callable[..., t.Any] | str | None = None538- ) -> t.Callable[[T_template_global], T_template_global] | T_template_filter:539- """Register a template global, available in any template rendered by the540- application. Equivalent to :meth:`.Flask.template_global`.563+ self, name: T_template_global | str | None = None564+ ) -> T_template_global | t.Callable[[T_template_global], T_template_global]:565+ """Decorate a function to register it as a custom Jinja global. The name566+ is optional. The decorator may be used without parentheses.567 542- .. versionadded:: 0.10568+ The :meth:`add_app_template_global` method may be used to register a569+ function later rather than decorating.570 544- :param name: the optional name of the global, otherwise the545- function name will be used.571+ The global is available in all templates, not only those under this572+ blueprint. Equivalent to :meth:`.Flask.template_global`.573+574+ :param name: The name to register the global as. If not given, uses the575+ function's name.576+577+ .. versionadded:: 0.10578 """579 if callable(name):548- # If name is callable, it is the function to register.549- # This is a shortcut for the common case of550- # @bp.add_template_global551- # def func():580+ self.add_app_template_global(name)581+ return name582 553- func = name554- self.add_app_template_global(func)555- return func556-583 def decorator(f: T_template_global) -> T_template_global:584 self.add_app_template_global(f, name=name)585 return f586 2 unmodified lines589 @setupmethod590 def add_app_template_global(591 self, f: ft.TemplateGlobalCallable, name: str | None = None592 ) -> None:567- """Register a template global, available in any template rendered by the568- application. Works like the :meth:`app_template_global` decorator. Equivalent to569- :meth:`.Flask.add_template_global`.593+ """Register a function to use as a custom Jinja global.594 571- .. versionadded:: 0.10595+ The :meth:`app_template_global` decorator can be used to register a function596+ by decorating instead.597 573- :param name: the optional name of the global, otherwise the574- function name will be used.598+ The global is available in all templates, not only those under this599+ blueprint. Equivalent to :meth:`.Flask.add_template_global`.600+601+ :param f: The function to register.602+ :param name: The name to register the global as. If not given, uses the603+ function's name.604+605+ .. versionadded:: 0.10606 """607 577- def register_template(state: BlueprintSetupState) -> None:578- state.app.jinja_env.globals[name or f.__name__] = f608+ def register_template_global(state: BlueprintSetupState) -> None:609+ state.app.add_template_global(f, name=name)610 580- self.record_once(register_template)611+ self.record_once(register_template_global)612 613 @setupmethod614 def before_app_request(self, f: T_before_request) -> T_before_request:615 """Like :meth:`before_request`, but before every request, not only those handled77 unmodified lines