带多个参数的应用程序模板筛选器

2024-05-05 20:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将两个参数传递给app_template_filter [docs]?如果我只使用一个参数,这个方法很有效。但在这种情况下,我需要两个。在

@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
    pass

^{pr2}$

错误:

TypeError: posts_page() takes exactly 2 arguments (1 given)

Tags: 方法idmodappdocs参数defpage
2条回答

虽然您可以使用上下文处理器,但它可能并不总是您想要的。在

接受答案中的文档片段说:

[Filters] may have optional arguments in parentheses.

那么,看看asker的模板过滤器:

@mod.app_template_filter('posts_page')
def posts(post_id, company_id):
    pass

以下内容在模板中有效:

^{pr2}$

Jijna 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.

过滤器设计为一次修改一个变量。您正在寻找^{}

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)

可以在模板中用作

^{pr2}$

您可以将此作为您的posts_page方法:

@app.context_processor
def posts_page():
    def _posts_page(post_id, company_id):
        # ...
        return value
    return dict(posts_page=_posts_page)

相关问题 更多 >