Is there a built-in Django template filter that finds the first value in a list to satisfy a condition?
Question: In a Django template, how do I return the first element of a list that matches
a condition? The list could be empty. I want to know if there is a filter that
finds the first element in an iterable to match a particular condition, then
stops checking, similar to Python's
[next](https://docs.python.org/2/library/functions.html#next)
(<http://stackoverflow.com/a/2364277/1337422>).

    
    
    >>> lis = ['a', 1, 40, 'three', 5]
    >>> next(x for x in lis if x == 1)
    1
    


Answer: There isn't a built in Django template filter that does this.

If it is a particular condition you want to match, then it would be easy to
write a [custom template
filter](https://docs.djangoproject.com/en/dev/howto/custom-template-
tags/#writing-custom-template-filters). For example:

    
    
    from django import template
    
    register = template.Library()
    
    @register
    def first_one_in_list(l):
    return next((x for x in l if x==1), default=None) # specify default to avoid stop iteration
    

If you want to specify an arbitrary condition in the template, I think you'd
need to do something hacky. The Django template language is designed to
prevent complex logic in templates.

