feat: support call template_filter without parens

This commit is contained in:
kadai0308 2025-05-17 12:17:18 +08:00
parent a5f9742398
commit 0a52b6b78d
2 changed files with 45 additions and 5 deletions

View File

@ -662,8 +662,8 @@ class App(Scaffold):
@setupmethod
def template_filter(
self, name: str | None = None
) -> t.Callable[[T_template_filter], T_template_filter]:
self, name: t.Callable[..., t.Any] | str | None = None
) -> t.Callable[[T_template_filter], T_template_filter] | T_template_filter:
"""A decorator that is used to register custom template filter.
You can specify a name for the filter, otherwise the function
name will be used. Example::
@ -672,10 +672,26 @@ class App(Scaffold):
def reverse(s):
return s[::-1]
The decorator also can be used without parentheses::
@app.template_filter
def reverse(s):
return s[::-1]
:param name: the optional name of the filter, otherwise the
function name will be used.
"""
if callable(name):
# If name is callable, it is the function to register.
# This is a shortcut for the common case of
# @app.template_filter
# def func():
func = name
self.add_template_filter(func)
return func
def decorator(f: T_template_filter) -> T_template_filter:
self.add_template_filter(f, name=name)
return f

View File

@ -129,6 +129,30 @@ def test_template_filter(app):
assert app.jinja_env.filters["my_reverse"] == my_reverse
assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"
@app.template_filter
def my_reverse_2(s):
return s[::-1]
assert "my_reverse_2" in app.jinja_env.filters.keys()
assert app.jinja_env.filters["my_reverse_2"] == my_reverse_2
assert app.jinja_env.filters["my_reverse_2"]("abcd") == "dcba"
@app.template_filter("my_reverse_custom_name")
def my_reverse_3(s):
return s[::-1]
assert "my_reverse_custom_name" in app.jinja_env.filters.keys()
assert app.jinja_env.filters["my_reverse_custom_name"] == my_reverse_3
assert app.jinja_env.filters["my_reverse_custom_name"]("abcd") == "dcba"
@app.template_filter(name="my_reverse_custom_name_2")
def my_reverse_4(s):
return s[::-1]
assert "my_reverse_custom_name_2" in app.jinja_env.filters.keys()
assert app.jinja_env.filters["my_reverse_custom_name_2"] == my_reverse_4
assert app.jinja_env.filters["my_reverse_custom_name_2"]("abcd") == "dcba"
def test_add_template_filter(app):
def my_reverse(s):