问题描述
我已经定义了一些过滤器,并经常使用它。我需要做一些A / B测试,在某些情况下,一些过滤器应该以不同的方式工作。最简单的方法是创建一个变量存储过滤器名称的模板。如下所示:
已经创建了一个名为filter_name的字符串变量。你应该创建一个过滤器,它会根据它来决定做什么。
{%set filter_name =' some_name'%}
{{my_value | myfilter(filter_name)}}
$ b $ myfilter(value,filtername):
if(filtername is'twice')
返回值* 2
其他
.....
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.
解决方案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 .....
这篇关于如何使用变量在jinja2模板中传递过滤器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!