Skip to content
Myr

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

3 files+227 added−178 removed

modified:docs/templating.rst+42 added-20 removed
135 unmodified lines
136using in this block.137138.. _registering-filters:139140Registering Filters141-------------------140Registering Filters, Tests, and Globals141---------------------------------------142143If you want to register your own filters in Jinja2 you have two ways to do144that. 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.143The Flask app and blueprints provide decorators and methods to register your own144filters, tests, and global functions for use in Jinja templates. They all follow145the same pattern, so the following examples only discuss filters.146148The following examples work the same and all reverse an object::147Decorate a function with :meth:`~.Flask.template_filter` to register it as a148template filter.149150 @app.template_filter # use the function name as filter name151 def reverse_filter(s):152 return s[::-1]150.. code-block:: python151154 @app.template_filter('reverse')152 @app.template_filter153 def reverse(s):154 return reversed(s)155156.. code-block:: jinja157158 {% for item in data | reverse %}159 {% endfor %}160161By default it will use the name of the function as the name of the filter, but162that can be changed by passing a name to the decorator.163164.. code-block:: python165166 @app.template_filter("reverse")167 def reverse_filter(s):156 return s[::-1]168 return reversed(s)169170A filter can be registered separately using :meth:`~.Flask.add_template_filter`.171The name is optional and will use the function name if not given.172173.. code-block:: python174175 def reverse_filter(s):159 return s[::-1]160 app.jinja_env.filters['reverse'] = reverse_filter176 return reversed(s)177162In case of the decorator the argument is optional if you want to use the163function name as name of the filter. Once registered, you can use the filter164in your templates in the same way as Jinja2's builtin filters, for example if165you have a Python list in context called `mylist`::178 app.add_template_filter(reverse_filter, "reverse")179167 {% for x in mylist | reverse %}168 {% endfor %}180For 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`183method.184185The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to186indicate that the registered functions will be avaialble to all templates, not187only when rendering from within the blueprint.188189The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be190modified directly, as you would when using Jinja outside Flask.191192193Context Processors194------------------195196To inject new variables automatically into the context of a template,
59 unmodified lines
modified:src/flask/sansio/app.py+82 added-86 removed
658 unmodified lines
659 f" endpoint function: {endpoint}"660 )661 self.view_functions[endpoint] = view_func662663 @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.675671 @app.template_filter()672 def reverse(s):673 return s[::-1]676 .. code-block:: python677675 The decorator also can be used without parentheses::678 @app.template_filter("reverse")679 def reverse_filter(s):680 return reversed(s)681677 @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.684681 :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 """684688 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 name691691 func = name692 self.add_template_filter(func)693 return func694692 def decorator(f: T_template_filter) -> T_template_filter:693 self.add_template_filter(f, name=name)694 return f695
2 unmodified lines
698 @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.703708 :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.706707 :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__] = f712713 @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.725726 .. code-block:: python727721 @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 True736730 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.739732 @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.742743 .. versionadded:: 0.10741742 :param name: the optional name of the test, otherwise the743 function name will be used.744 """745745 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]748752 func = name753 self.add_template_test(func)754 return func755749 def decorator(f: T_template_test) -> T_template_test:750 self.add_template_test(f, name=name)751 return f752
2 unmodified lines
755 @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.760769 .. versionadded:: 0.10761 The :meth:`template_test` decorator can be used to register a function762 by decorating instead.763771 :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.767768 .. versionadded:: 0.10769 """770 self.jinja_env.tests[name or f.__name__] = f771772 @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.784784 @app.template_global()785 def double(n):786 return 2 * n785 .. code-block:: python786788 The decorator also can be used without parentheses::789787 @app.template_global788 def double(n):789 return 2 * n790794 .. versionadded:: 0.10791 The :meth:`add_template_global` method may be used to register a792 function later rather than decorating.793796 :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.796797 .. 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 name802806 func = name807 self.add_template_global(func)808 return func809803 def decorator(f: T_template_global) -> T_template_global:804 self.add_template_global(f, name=name)805 return f806
2 unmodified lines
809 @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.814823 .. versionadded:: 0.10815 The :meth:`template_global` decorator can be used to register a function816 by decorating instead.817825 :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.821822 .. versionadded:: 0.10823 """824 self.jinja_env.globals[name or f.__name__] = f825826 @setupmethod
186 unmodified lines
modified:src/flask/sansio/blueprints.py+103 added-72 removed
438 unmodified lines
439 **options,440 )441 )442443 @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.455450 :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.458459 The filter is available in all templates, not only those under this460 blueprint. Equivalent to :meth:`.Flask.template_filter`.461462 :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 name468460 func = name461 self.add_app_template_filter(func)462 return func463469 def decorator(f: T_template_filter) -> T_template_filter:470 self.add_app_template_filter(f, name=name)471 return f472
2 unmodified lines
475 @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.480478 :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.483484 The filter is available in all templates, not only those under this485 blueprint. Equivalent to :meth:`.Flask.add_template_filter`.486487 :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 """491482 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)494485 self.record_once(register_template)495 self.record_once(register_template_filter)496497 @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.509494 .. versionadded:: 0.10510 The :meth:`add_app_template_test` method may be used to register a511 function later rather than decorating.512496 :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`.515516 :param name: The name to register the filter as. If not given, uses the517 function's name.518519 .. 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]524506 func = name507 self.add_app_template_test(func)508 return func509525 def decorator(f: T_template_test) -> T_template_test:526 self.add_app_template_test(f, name=name)527 return f528
2 unmodified lines
531 @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.536524 .. versionadded:: 0.10537 The :meth:`app_template_test` decorator can be used to register a538 function by decorating instead.539526 :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`.542543 :param f: The function to register.544 :param name: The name to register the test as. If not given, uses the545 function's name.546547 .. versionadded:: 0.10548 """549530 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)552533 self.record_once(register_template)553 self.record_once(register_template_test)554555 @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.567542 .. versionadded:: 0.10568 The :meth:`add_app_template_global` method may be used to register a569 function later rather than decorating.570544 :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`.573574 :param name: The name to register the global as. If not given, uses the575 function's name.576577 .. 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 name582553 func = name554 self.add_app_template_global(func)555 return func556583 def decorator(f: T_template_global) -> T_template_global:584 self.add_app_template_global(f, name=name)585 return f586
2 unmodified lines
589 @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.594571 .. versionadded:: 0.10595 The :meth:`app_template_global` decorator can be used to register a function596 by decorating instead.597573 :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`.600601 :param f: The function to register.602 :param name: The name to register the global as. If not given, uses the603 function's name.604605 .. versionadded:: 0.10606 """607577 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)610580 self.record_once(register_template)611 self.record_once(register_template_global)612613 @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 handled
77 unmodified lines