Skip to content

Instantly share code, notes, and snippets.

@mativs
Created May 24, 2012 13:43
Show Gist options
  • Save mativs/2781616 to your computer and use it in GitHub Desktop.
Save mativs/2781616 to your computer and use it in GitHub Desktop.
Template tag filters to call an instance method with 'user' parameter
from django import template
register = template.Library()
@register.filter
def with_user(instance, user):
"""
stores the user in the instance attribute '_onuser' wether exists or not.
"""
setattr(instance, "_onuser", user)
return instance
@register.filter
def call_method(instance, method):
"""
calls the instance method 'method' passing the argument 'user' with the instance
variable '_onuser'.
Usage: {{ instance|with_user:user|call_method:"my_method_name" }}
"""
method = getattr(instance, method)
if hasattr(instance, "_onuser"):
try:
to_return = method(user=instance._onuser)
except:
to_return = method()
return to_return
return method()
from django.test import TestCase
from django.template import Template, Context
from django.contrib.auth.models import User
class OnUserToTest():
def usernames(self, user=None):
basic = ['basico']
if user:
basic.append(user.username)
return basic
class OnUserTestCase(TestCase):
def test_with_user_method(self):
u = User(username='prueba')
c = Context({ 'test': OnUserToTest(), 'user':u})
t = Template ("{% load users_extras %}{% for username in test|with_user:user|call_method:'usernames' %}{{username}}{% endfor %}")
r = t.render(c)
self.assertEquals(r, 'basicoprueba' )
def test_no_parameters(self):
t = Template ("{% load users_extras %}{% for username in test.usernames %}{{username}}{% endfor %}")
u = User(username='prueba')
c = Context({ 'test': OnUserToTest(), 'user':u})
r = t.render(c)
self.assertEquals(r, 'basico' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment