Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use variable to pass filter name in jinja2 templates

Tags:

filter

jinja2

I have defined some filters and use it very often. I need to do some A/B tests and for this in some situations some of filters should work in different way.

Easiest way to do this would be create a variable in template which store a filter name. something like this:

{% set filter_name = 'some_name' %}
{{ my_value|filter_name }}

But when I try this, I get an error:

TemplateAssertionError: no filter named 'filter_name'

Please help me to find a solution.

like image 206
Kania Avatar asked Oct 14 '13 13:10

Kania


1 Answers

By doing {% set filter_name = 'some_name' %}, you have create a string variable named "filter_name". You should create a filter which takes one more argument on basis of which it decides what to do.

{% set filter_name = 'some_name' %}
{{ my_value|myfilter(filter_name) }}


def myfilter(value, filtername):
    if(filtername is 'twice')
        return value*2
    else
        .....
like image 77
mohit jain Avatar answered Oct 23 '22 21:10

mohit jain