Ticket #12329: template.py

File template.py, 1.5 KB (added by gurunars, 15 years ago)

The source code of the decorator

Line 
1#Idea and implementation by Anton Berezin
2
3from django.http import HttpResponse
4from django.template import Context, loader
5import re #regexp
6
7
8#The response object that can hold the context
9class HttpResponseHolder(HttpResponse):
10 context = {} #make sure that it is a dictianory
11
12
13#Adds a template to a view
14class template(object):
15
16 def __init__(self, template_name = None):
17 self.template_name = template_name
18
19 def __call__(self, function):
20 def function_wrapper(*args):
21 return_val = function(*args)
22 #get a proper template name
23 if self.template_name == None: #if template name is not defined derive it from package name and view function name
24 array = re.split("\.", function.__module__) #split into array with elements like [0]=project_name, [1]=package_name, [2]=file_name (where the function lives)
25 package_name = array[1]
26 self.template_name = "%s/%s.html" %(package_name, function.__name__)
27 #compose the response
28 template = loader.get_template(str(self.template_name))
29 if isinstance(return_val, HttpResponseHolder):
30 return HttpResponse(template.render(Context(return_val.context)))
31 elif isinstance(return_val, dict):
32 context = Context(return_val)
33 return HttpResponse(template.render(context))
34 elif isinstance(return_val, HttpResponse):
35 return return_val
36 else:
37 return
38 return function_wrapper
Back to Top