1

Not sure if anyone has had experience with a good solution to rendering templates specifically for mobile devices using django.

I wrote a middleware request processor that uses regex to detect whether it is a mobile browser or not. I am currently setting a boolean attribute on the request so that I can use it further down the pipe. But really my business logic is the same I just want to use a different set of templates.

Is there a way for me to add a new template directory to settings.TEMPLATE_DIRS in the middleware processor, so that a mobile user would get the views I choose to rewrite, but everything else would fall back to the default template directories. But I need to make sure it doesn't persist between requests.

If i added a directory, would settings continue to hold onto it between requests?

..and if so, is this the right solution (checking the browser agent, adding an additional template folder, and then removing it at the end of each request)?

MattoTodd
  • 14,467
  • 16
  • 59
  • 76

1 Answers1

2

Dynamically modifying the template search path is a great way to handle this. It's not hard to define your own template loader and add it to the TEMPLATE_LOADERS in settings.py. The tricky part of this is handling the fact you may be running in a multi-threaded environment, and you don't have a way to pass your request directly to the template loader.

The way around it is to store the request, a flag, or simply the directories to add to the path in a thread local variable, and reference that thread local variable from a custom template loader. Here's a blog post about creating template loaders, I can vouch for the fact it's pretty easy and works. Here's an even better one about doing exactly what you need.

I guess i didn't specifically point out that you probably do not want to try to change settings.TEMPLATE_DIRS per request, you will get wierd results at best.

easel
  • 3,982
  • 26
  • 28
  • how would i get access to the local variable while i was inside the load_template_source function? or how do i set a local variable that i can access in the loader – MattoTodd Mar 20 '11 at 04:25
  • A threadlocal is really a global variable, so it's "just there" but you can be confident you'll only be getting the one relevant to the currently executing request. Quite a few details here http://stackoverflow.com/questions/1057252/django-how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clea – easel Mar 20 '11 at 04:27
  • This blog post has it all. I added it to the answer. http://opensource.washingtontimes.com/blog/2010/feb/17/loading-templates-based-request-headers-django/ – easel Mar 20 '11 at 04:31
  • Thanks Again. I wrote up my specific implementation http://sullerton.com/2011/03/django-mobile-browser-detection-middleware/ – MattoTodd Mar 20 '11 at 18:51