Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app_template_filter with multiple arguments

How can I pass two argument to app_template_filter [docs]? This works well if i use only one argument. But in this case, i need two.

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

{{ post.id, post.company.id | posts_page }}

Error:

TypeError: posts_page() takes exactly 2 arguments (1 given)
like image 231
user455318 Avatar asked May 19 '15 22:05

user455318


2 Answers

From the 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.

Filters are designed to modify one variable at a time. You're looking for a context processor:

Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions)

For example,

@app.context_processor
def add():
    def _add(int1, int2):
        return int(int1) + int(int2)
    return dict(add=_add)

can be used in the template as

{{ add(a, b) }}

You can adopt this as your posts_page method:

@app.context_processor
def posts_page():
    def _posts_page(post_id, company_id):
        # ...
        return value
    return dict(posts_page=_posts_page)
like image 114
Celeo Avatar answered Oct 28 '22 14:10

Celeo


While you may use a context processor, it may not always be what you want.

The docs snippet in the accepted answer says:

[Filters] may have optional arguments in parentheses.

So, looking at the asker's template filter:

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

The following is valid in the template:

{{ post.id|posts_page(post.company_id) }}
like image 29
multithr3at3d Avatar answered Oct 28 '22 13:10

multithr3at3d