6

I would like to somehow instrument a mako.lookup.TemplateLookup such that it applies certain preprocessors only for certain file extensions.

Specifically, I have a haml.preprocessor that I would like to apply to all templates whose file name ends with .haml.

Thanks!

Mike Boers
  • 6,665
  • 3
  • 31
  • 40

1 Answers1

4

You should be able to customize TemplateLookup to get the behavior you want.

customlookup.py

from mako.lookup import TemplateLookup
import haml

class Lookup(TemplateLookup):
    def get_template(self, uri):
        if uri.rsplit('.')[1] == 'haml':
            # change preprocessor used for this template
            default = self.template_args['preprocessor']
            self.template_args['preprocessor'] = haml.preprocessor
            template = super(Lookup, self).get_template(uri)
            # change it back
            self.template_args['preprocessor'] = default
        else:
            template = super(Lookup, self).get_template(uri)
        return template

lookup = Lookup(['.'])
print lookup.get_template('index.haml').render()

index.haml

<%inherit file="base.html"/>

<%block name="content">
  %h1 Hello
</%block>

base.html

<html>
  <body>
    <%block name="content"/>
  </body>
</html>
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
  • I have finally attempted to implement this instead of the hack that I was using, and I hit a problem. This changes the preprocessor for the entire lookup, which affects all templates in the inheritance chain. In my case, I'm slowly transitioning the templates into HAML, and so most of the chain is not valid HAML. – Mike Boers Jan 25 '12 at 18:43
  • In my last two examples the haml preprocessor is only used when the template has the `.haml` extension, you should be able to mix haml/html templates. – Zach Kelling Jan 25 '12 at 19:53
  • Template lookups due to inheritance or <%include /> tags use whichever Lookup loaded the first template. If I `get_template("something.haml")` and then inherit from something that isn't HAML, it will fail. – Mike Boers Jan 25 '12 at 22:41
  • Should work fine, I wonder what you are doing? I'll update my example to illustrate this. – Zach Kelling Jan 25 '12 at 23:48
  • I'm conveniently reading your answer wrong. Totally my bad. Before asking the question I came up with something very similar to what you have ended up with here. My only change is to add a RLock around changing `self.template_args['preprocessor']` to avoid race conditions in the threaded environment I'm in. Cheers! – Mike Boers Jan 26 '12 at 02:46