App_template_filter with multiple arguments

How to pass two arguments 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) 
+7
source share
2 answers

From Jijna docs ,

Variables can be changed by filters. Filters are separated from the variable by the symbol (|) and may have optional arguments in parentheses. Several filters can be chained. The output of one filter is applied to the next.

Filters are designed to change one variable at a time. Are you looking for context processor :

Variables are not limited to values; the context processor can also create functions available for templates (since Python allows you to pass functions)

For instance,

 @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 take 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) 
+6
source

Although you can use a context processor, this may not always be what you want.

In the accepted answer, a fragment of documents:

[Filters] may have optional arguments in parentheses.

So, looking at the filter of the author’s template:

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

The following applies in the template:

 {{ post.id|posts_page(post.company_id) }} 
+8
source

Source: https://habr.com/ru/post/987534/


All Articles