views:

54

answers:

1

Hi, I' m trying to build a Django TemplateLoader, but I can't make it 'see' either the current Context or Request, so I can't really do much with it.

Does anyone know how I can make a Django TemplateLoader do this?

Many Thanks

Joe

+1  A: 

The place to make decisions about templates is in your view. There, you have access to the request, and can dynamically construct a template name depending on whatever conditions you like. E.g.,

def my_view(request, ...):
  ...
  template_name = 'template.html'
  if is_mobile(request): template_name = 'mobile_' + template_name
  template = get_template(template_name)
  context = RequestContext(request, {...})
  return HttpResponse(template.render(context))

Where you provide the is_mobile(). Better would be to provide a method that takes a request and template name, and returns one appropriately modified (so that you can encode that logic once, rather than scattering across several views).

You might also get some leverage from select_template(), which takes a list of candidate template names, returning a template for the first one it finds.

Dave W. Smith
yeah i have something similar currently in place as a replacement render_to_response (called template), but how do I apply that to things likedjango.contrib.auth.views.login as they use the proper render_to_response
Joe Simpson
You don't need to invoke django.contrib.auth.views.login directly from a urlpattern. You can wrap it an other view that uses the request to figure out what template_name to pass it.
Dave W. Smith
Oh okay. I will look at doing that then. Thanks very much :)
Joe Simpson