0

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://stackoverflow.com/a/2364277/1337422).

>>> lis = ['a', 1, 40, 'three', 5]
>>> next(x for x in lis if x == 1)
1
Community
  • 1
  • 1
sgarza62
  • 5,998
  • 8
  • 49
  • 69

1 Answers1

2

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. 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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516