Search code examples
jinja2

Is there any way to get the "filter name" inside the common custom filter function defined against it


I have written generic custom filters.

def common_custom_filter_func(**args, **kwargs):
     print(filter name)

And there are many filters with different names mapped to the same function

{
"filter1": common_custom_filter_func,
"filter2": common_custom_filter_func,
}

Is there any way I can get my filter name inside the filter function when its called? For example, I need to catch the name filter1 inside common_custom_filter_func when the below template is called. And respectively for filter2

{{ data | filter1 }} ----> prints filter1
{{ data | filter2 }} ----> prints filter2

I tried pass_context but it does not have any attribute that has the caller filter name.


Solution

  • You can't get the name by which a filter function was called from within the function by default.

    You could pass in the name as a parameter, something like:

    import jinja2
    
    from functools import partial
    
    
    def common_custom_filter_func(filter_name, value):
        return f"{filter_name}: {value}"
    
    
    def main():
        env = jinja2.Environment(loader=jinja2.FileSystemLoader("templates"))
        env.filters |= {
            "filter1": partial(common_custom_filter_func, "filter1"),
            "filter2": partial(common_custom_filter_func, "filter2"),
            "filter3": partial(common_custom_filter_func, "filter3"),
        }
        t = env.get_template("example.j2.txt")
        print(t.render())
    
    
    if __name__ == "__main__":
        main()
    

    Assuming that example.j2.txt looks like this:

    This is a test.
    
    Using filter1: {{ "some data" | filter1 }}
    
    Using filter2: {{ "more data" | filter2 }}
    

    This will produce:

    This is a test.
    
    Using filter1: filter1: some data
    
    Using filter2: filter2: more data