尝试做这样的事情:
filters = ['foo', 'bar']
然后在Jinja2模板中:
<p>{{value|filter for filter in filters}}</p>
foo
和bar
是我定义的Jinja2过滤器。
这不起作用,但似乎应该很容易实现。有什么想法吗?
答案 0 :(得分:0)
假设你正在使用flask(否则只是调整你的过滤器,但是你可以创建一个过滤器来应用命名过滤器。
在您的过滤器定义中(例如my_filters.py
):
def filter1(x):
return 'filtered1( {} )'.format(x)
app.jinja_env.filters['filter1'] = filter1 # Register filter
def filter2(x):
return 'filtered2( {} )'.format(x)
app.jinja_env.filters['filter2'] = filter2
# Create a filter to apply a list of filters by name...
def apply_filters_by_name(x, filter_names):
result = x
# Loop through filter names and apply them sequentially
for fname in filter_names:
# Get the filter function matching this name
filter_function = app.jinja_env.filters[fname]
# Apply the filter
result = filter_function(result) # apply filter
return result
app.jinja_env.filters['apply_filters_by_name'] = apply_filters_by_name
...在您的HTML模板中,例如:
{% set some_filter_names = ['filter1', 'filter2'] %}
{{ 'hello world'|apply_filters_by_name(some_filter_names) }}
在这里,我在模板中设置了some_filter_names,但显然你也可以将其作为变量传递。
结果是:
filtered2( filtered1( hello world ) )