Passing arguments to functions in Django TemplateTags: django, web, python — 18th of November 2009


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


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".
To call multiple arguments do {{ meeting|args:arg1|args:arg2|call:"getPrice" }}.