Created
April 18, 2012 21:26
-
-
Save kmike/2416695 to your computer and use it in GitHub Desktop.
TemplateResponse subclass with extra goodies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.template.response import TemplateResponse | |
class show(TemplateResponse): | |
""" | |
TemplateResponse subclass with extra goodies. It is intended to be used | |
as a better replacement of `django.shortcuts.render`. | |
""" | |
def resolve_template(self, template): | |
""" | |
Accepts only path-to-template (unlike TemplateResponse method). | |
For ajax requests it tries a template in 'ajax' subfolder first. | |
E.g. if request is ajax then | |
show(request, 'myapp/index.html') | |
will try 'myapp/ajax/index.html' first and fallback to 'myapp/index.html' | |
if ajax template is not found. | |
""" | |
assert isinstance(template, basestring) | |
if self._request.is_ajax(): | |
if '/' in template: | |
path, name = template.rsplit('/', 1) | |
ajax_template = "/".join((path, 'ajax', name)) | |
else: | |
ajax_template = "ajax/"+template | |
template = [ajax_template, template] | |
return super(show, self).resolve_template(template) | |
def with_template(self, template): | |
""" | |
Sets self.template_name to `template` and returns self, | |
so instead of this:: | |
def foo(request): | |
return TemplateResponse(request, 'foo.html') | |
def bar(request): | |
response = foo(request) | |
response.template_name = 'bar.html' | |
return response | |
it is possible to write this:: | |
def foo(request): | |
return show(request, 'foo.html') | |
def bar(request): | |
return foo(request).with_template('bar.html') | |
""" | |
self.template_name = template | |
return self | |
def with_context(self, context): | |
""" | |
Updates self.context_data with `context` and returns self, | |
so instead of this:: | |
def foo(request): | |
return TemplateResponse(request, 'foo.html') | |
def bar(request): | |
response = foo(request) | |
response.context_data['bar'] = 'bar' | |
return response | |
it is possible to write this:: | |
def foo(request): | |
return show(request, 'foo.html') | |
def bar(request): | |
return foo(request).with_context(bar='bar') | |
""" | |
self.context_data = self.context_data or {} | |
self.context_data.update(context) | |
return self |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment