Passing arguments to functions in Django Template

Tags: django, web, python | Comments (3) | Posted on Wednesday 18th of November 2009 04:27:40 PM

Why?

Because sometimes your output data is based on certain arguments. For example when you want to display the price for a meeting, but the price differs based on the type of user. So when you call getPrice on the meeting you need to pass in the user. Ex:
def getPrice(self, user):
   if (user.isStudent):
      return self.studentFee
   else:
      return self.nonStudentFee
And to display the result of that in django template we write {{ meeting.getPrice }} but this gives us no option to pass arguments, thats what we're solving (hack).

How?

This is the template code being used
def callMethod(obj, methodName):
    method = getattr(obj, methodName)

    if obj.__dict__.has_key("__callArg"):
        ret = method(*obj.__callArg)
        del obj.__callArg
        return ret
    return method()

def args(obj, arg):
    if not obj.__dict__.has_key("__callArg"):
        obj.__callArg = []
    
    obj.__callArg += [arg]
    return obj

register.filter("call", callMethod)
register.filter("args", args)
And now we can pass the arguments to getPrice by writing {{ meeting|args:user|call:"getPrice" }}. So we set the arguments using "args" and then call the function using "call".
This works fine with multiple arguments.

Hi... I tried the above code in my application... i need to pass 2 arguments to a function... so while defining args i defined like this:
Apoorva Bade on Friday 11th of June 2010 01:34:07 AM
Hi... I tried the above code in my application... i need to pass 2 arguments to a function... so while defining args i defined like this: def args(obj,arg1,arg2) and in the template i called the function like this: {{ users|args: username,users.Name|call:"getNameBoolean"}} But i get an error which says: " args requires 2 arguments, 0 provided" Is variable passing worng here? Thanks for your help
Apoorva Bade on Friday 11th of June 2010 01:35:51 AM
MOST. USEFUL. SNIPPET. EVER. A million times thank you.
Agostino Carandente on Tuesday 15th of June 2010 04:28:05 PM
Click here to add your own comment!