1

My problem started when the extends tag in a Django template could not reference a base template in a parent dir. This question1 has a very good answer to the problem, but it disables the implicit template caching provided by the default template.render function in appengine.

The author of the answer also mentions that it would be fairly simple to implement this template caching, but I feel tampering with this kind of functionality will produce bugs in the future. Any suggestions?

Community
  • 1
  • 1
cabe56
  • 404
  • 2
  • 14
  • From that answer it sounds like you're trying to use the django templating engine without the rest of django? Cuz if you just use django, then you're done. – dragonx May 23 '12 at 21:19
  • Yeah, with appengine you can use django templates without using the whole thing. – cabe56 May 23 '12 at 22:10
  • 2
    Have you considered switching to Jinja2? It's a near clone of Django templates, is included in the 2.7 runtime, and doesn't require you to mess with django config. – Nick Johnson May 24 '12 at 01:27

1 Answers1

0

All of our template dirs are sub-folders of one template dir, so we just needed to get the loader to look there first.

I haven't tested if/how this breaks the template caching, but it doesn't change the behaviour AFAICT.

We did it by extending the base loader with a module alternative_path.py like this:

class Loader(filesystem.Loader):
"""
Looks for templates in an alternative path.

Allows a template to extend a template which is located in a specified views path.
"""

is_usable = True
__view_paths = None

def __init__(self, views_path):
    if Loader.__view_paths is None:
        Loader.__view_paths = [views_path]

def get_alternative_template_sources(self, template_name):
    for template_dir in Loader.__view_paths:
        try:
            yield safe_join(template_dir, template_name)
        except UnicodeDecodeError:
            # The template dir name was a bytestring that wasn't valid UTF-8.
            raise
        except ValueError:
            # The joined path was located outside of this particular
            # template_dir (it might be inside another one, so this isn't
            # fatal).
            pass

def get_template_sources(self, template_name, template_dirs):
    return itertools.chain(
        filesystem.Loader.get_template_sources(self, template_name, template_dirs),
        Loader.get_alternative_template_sources(self, template_name))

Then in the same module:

_loader = Loader

Then in main.py:

def main():
    views_path = os.path.join(os.path.dirname(__file__), 'templates')
    settings.TEMPLATE_LOADERS = (('web.rich.templates.alternative_path.Loader', views_path),
                             'django.template.loaders.filesystem.Loader',
                             'django.template.loaders.app_directories.Loader')
Campey
  • 390
  • 2
  • 10