Code

Opened 4 years ago

Closed 4 years ago

#12815 closed (fixed)

Add a lazy TemplateResponse

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

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

Attachments (0)

Change History (4)

comment:1 Changed 4 years ago by russellm

  • Has patch set
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design decision needed

comment:2 Changed 4 years ago by jezdez

  • Needs tests set

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

comment:3 Changed 4 years ago by carljm

  • Cc carljm added

comment:4 Changed 4 years ago by russellm

  • Resolution set to fixed
  • Status changed from new to closed

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.