Login or Sign up

Django template filter to find if all members of an iterable have a certain attr

Posted by: skyl on Dec. 30, 2010

I like to moan on about how django templates can be too limiting sometimes. However, it's super easy to implement neat little filters once you quit b!tching for a couple of minutes and read the docs

I was thinking about pain in the template or pain in the models. Instead, I wrote this satisfying little template filter:

from django import template
register = template.Library()

def all_have(value, arg):
  """Do all the members of the iterable have a certain value?

      {{ mylist|all_have:"certain_attr_bools_to_True" }}

  returns True or False.
  """
  return all([getattr(a, arg) for a in value])

register.filter('all_have', all_have)

Comments on This Post:

Please Login (or Sign Up) to leave a comment