You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在通用自定义过滤器函数中获取调用它的过滤器名称?

解决方法

要让通用过滤器函数获取到调用它的过滤器名称,你可以通过闭包或者functools.partial给函数绑定对应的名称,以下是具体实现:

方案一:闭包生成带名称的过滤器函数

先写一个生成器函数,接收过滤器名称作为参数,返回绑定了该名称的过滤器函数:

def create_filter(filter_name):
    def common_custom_filter_func(value, *args, **kwargs):
        print(filter_name)
        # 这里编写你的过滤逻辑,比如返回处理后的value
        return value
    return common_custom_filter_func

然后在过滤器映射中,用这个生成器创建对应名称的过滤器:

{
    "filter1": create_filter("filter1"),
    "filter2": create_filter("filter2"),
}

当模板调用{{ data | filter1 }}时,函数内部会打印filter1;调用{{ data | filter2 }}时则打印filter2。

方案二:用functools.partial绑定名称

借助functools.partial把过滤器名称作为固定参数传递给通用函数:

首先修改通用函数,新增filter_name参数:

from functools import partial

def common_custom_filter_func(filter_name, value, *args, **kwargs):
    print(filter_name)
    # 编写你的过滤逻辑
    return value

在过滤器映射时,用partial绑定对应的名称:

{
    "filter1": partial(common_custom_filter_func, "filter1"),
    "filter2": partial(common_custom_filter_func, "filter2"),
}

模板调用时会自动把data作为第二个参数传入,函数就能拿到对应的过滤器名称。

注意事项

  • 原函数定义中的**args是语法错误,Python中可变参数需区分*args(位置可变参数)和**kwargs(关键字可变参数),不能同时以**开头。
  • 若在Django等框架中注册过滤器,两种方案均能直接适配框架的过滤器注册逻辑。

内容的提问来源于stack exchange,提问作者satish mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:15:11