Custom jinja2 filter for iterator

前端 未结 1 1955
滥情空心
滥情空心 2021-01-12 10:18

How do I most efficiently write a custom filter for Jinja2 that applies to an iterable like the built-in \'sort\' filter, for use in a for loop in the template?

For

相关标签:
1条回答
  • 2021-01-12 10:53

    The same way you'd write any other filter. Here's an example that should get you started:

    from jinja2 import Environment, Undefined
    
    def custom_sort(iterable, somearg):
        if iterable is None or isinstance(iterable, Undefined):
            return iterable
    
        # Do custom sorting of iterable here
    
        return iterable
    
    # ...
    
    env = Environment()
    env.filters['customsort'] = custom_sort
    

    Don't worry about efficiency until it becomes a problem. The template engine is unlikely to be the bottle-neck in any case.

    0 讨论(0)
提交回复
热议问题