views:

129

answers:

2

Is there any way to make Django's template loader run all templates it loads (i.e. directly or via extend/include) through SHPAML if it figures the HTML is out of date?

I know how to invoke SHPAML recursively over an entire directory, but I would prefer to be able to run it on demand so I don't have to remember to sync the HTML every time I change the SHPAML source.

I guess invoking SHPAML from manage.py would work too (at least for test servers), but being able to hack into Django's template engine and make it run every file it loads through a preprocessor would be nicer.

+3  A: 

I suspect you can achieve what you want by inheriting from django.template.loaders.app_directories.Loader (or whatever loader you use) and overwriting the load_template_source method, e.g.:

from django.template.loaders.app_directories import Loader
from shpaml import convert_text

class SHPAMLLoader(Loader):
    def load_template_source(self, *args, **kwargs):
        shpaml_source = super(SHPAMLLoader, self).load_template_source(*args, **kwargs)
        html = convert_text(shpaml_source)
        return html

Then put your loader at the beginning of the TEMPLATE_LOADERS tuple in your settings.py. Of course, you will be doing the SHPAML to HTML dance every time a template is loaded, so you may see some overhead. The upcoming Django 1.2 features template caching, which could help mitigating that overhead...

Disclaimer: this code is completely untested, sorry.

piquadrat
This isn't quite what I was hoping for, but it's pretty close. In particular it doesn't help with the caching problem (templates should be preprocessed only when the source file has changed, otherwise the preprocessed file should be loaded, not the SHPAML source). It's probably a step in the right direction, though.
Alan
+1  A: 

Just created a project based on the snippet in piquadrat's answer. It's a little more feature complete and supports django 1.1 and 1.2 (probably 1.0 as well)

Thought it might come in handy for the future :)

Jiaaro