Opened 15 years ago

Closed 14 years ago

#12815 closed (fixed)

Add a lazy TemplateResponse

Reported by: Russell Keith-Magee Owned by: nobody
Component: Core (Other) Version:
Severity: Keywords:
Cc: Carl Meyer Triage Stage: Design decision needed
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Proposal from Simon Willison:

Summary: Add a TemplateResponse class - a response that contains a template and context, but doesn't evaluate the template until it is required (or explicitly 'baked'). This allows middlewares, decorators, or view wrappers to change the template.


The original proposal comes from this django-users thread, in the context of making CSRF easier to use. Simon said:

I've been experimenting recently with a TemplateResponse class which lets you do this:

def view(request): 
    return TemplateResponse(request, 'my_template.html', {'foo': 'bar'}) 

It's an HttpResponse class that's designed to be lazily evaluated. This makes it really useful for subclassing - you can do things like this:

class MyGenericView(object): 
   def view(self, request): 
       # Do something complicated 
       return TemplateResponse(request, 'my_template.html', {'foo': 'bar'}) 
class MyCustomisedView(object): 
   def view(self, request): 
       response = super(MyCustomisedView, self).view(request) 
       response.context['foo'] = 'baz' 
       if is_mobile_phone(request): 
           response.template = 'my_mobile_template.html' 
       return response 

This pattern would be particularly valuable for customising the admin, which currently uses nasty extra_context argument hacks to achieve something that isn't nearly as useful.

My current implementation of TemplateResponse is here - there's a SimpleTemplateResponse as well which doesn't use RequestContext (but has a more verbose name to discourage its use).

Change History (4)

comment:1 by Russell Keith-Magee, 15 years ago

Has patch: set
Triage Stage: UnreviewedDesign decision needed

comment:2 by Jannis Leidel, 15 years ago

Needs tests: set

For the record I'm +1 on that, really like the idiom.

comment:3 by Carl Meyer, 15 years ago

Cc: Carl Meyer added

comment:4 by Russell Keith-Magee, 14 years ago

Resolution: fixed
Status: newclosed

(In [14850]) Fixed #12815 -- Added TemplateResponse, a lazy-evaluated Response class. Thanks to Simon Willison for the original idea, and to Mikhail Korobov and Ivan Sagalaev for their assistance, including the draft patch from Mikhail.

Note: See TracTickets for help on using tickets.
Back to Top