app_template_filter 有多个参数
app_template_filter with multiple arguments
如何将两个参数传递给 app_template_filter
(doc)?如果我只使用一个参数,这很有效。但在这种情况下,我需要两个。
@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
pass
{{ post.id, post.company.id | posts_page }}
错误:
TypeError: posts_page() takes exactly 2 arguments (1 given)
来自Jinja docs,
Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.
过滤器旨在一次修改一个变量。您正在寻找 context processor
:
Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions)
例如,
@app.context_processor
def add():
def _add(int1, int2):
return int(int1) + int(int2)
return dict(add=_add)
可以在模板中使用
{{ add(a, b) }}
您可以采用此作为您的 posts_page
方法:
@app.context_processor
def posts_page():
def _posts_page(post_id, company_id):
# ...
return value
return dict(posts_page=_posts_page)
虽然您可以使用上下文处理器,但它可能并不总是您想要的。
接受的答案中的文档片段说:
[Filters] may have optional arguments in parentheses.
因此,查看提问者的模板过滤器:
@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
pass
以下在模板中有效:
{{ post.id|posts_page(post.company_id) }}
如何将两个参数传递给 app_template_filter
(doc)?如果我只使用一个参数,这很有效。但在这种情况下,我需要两个。
@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
pass
{{ post.id, post.company.id | posts_page }}
错误:
TypeError: posts_page() takes exactly 2 arguments (1 given)
来自Jinja docs,
Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.
过滤器旨在一次修改一个变量。您正在寻找 context processor
:
Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions)
例如,
@app.context_processor
def add():
def _add(int1, int2):
return int(int1) + int(int2)
return dict(add=_add)
可以在模板中使用
{{ add(a, b) }}
您可以采用此作为您的 posts_page
方法:
@app.context_processor
def posts_page():
def _posts_page(post_id, company_id):
# ...
return value
return dict(posts_page=_posts_page)
虽然您可以使用上下文处理器,但它可能并不总是您想要的。
接受的答案中的文档片段说:
[Filters] may have optional arguments in parentheses.
因此,查看提问者的模板过滤器:
@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
pass
以下在模板中有效:
{{ post.id|posts_page(post.company_id) }}