Kreshnik
Kreshnik

Reputation: 2831

Django: custom template filter

How can i create a simple filter to extract values from a dictionary like this:

PHANTOM_TYPE_CHOICES = (
    (1, 'Type 1'),
    (2, 'Type 2'),
)

that works with django 1.4:

I've tried this:

from django.template import Library    
register = Library() 
    ...

def get(d, key):
    return d.get(key, '')

register.filter(key)

..but it doesn't work! (it gives me the following error: 'function' object has no attribute 'filter')

Any ideas?

Upvotes: 0

Views: 725

Answers (2)

Mikael
Mikael

Reputation: 3236

In your code example you are trying to register a filter pointing to the method "key" however the method's name is "get"

Replace

register.filter(key)

with

register.filter(get)

or use the decorator

@register.filter()
def get(d, key):
    return dict(d).get(key, '')

Upvotes: 1

Andreas Neumeier
Andreas Neumeier

Reputation: 326

Have you tried:

register.filter('key', get)

Upvotes: 1

Related Questions