Login

Mako support as decorator

Author:
rmt
Posted:
November 7, 2007
Language:
Python
Version:
.96
Tags:
mako
Score:
2 (after 2 ratings)

This snippet allows you to use @mako("templatename.mako") to define a mako template to use.

Your python method just has to return a dictionary that will be passed to mako's context, after the addition of the "request" variable to the dictionary. If you return a non-False non dictionary object, it will return that instead of trying to render the template. The request variable is automatically added to the template's context.

It also searches the current application's mako_templates/ subdirectory first before searching under the current directories mako_templates/, and does not use other application's mako_templates/ subdirectories at all.

On Mako exceptions, it will display the Mako error page when debugging is enabled (hoping for extensible exception handling in the future to keep consistency)

I got the idea from a CherryPy tool.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# makodecorator.py
# License: None, public domain
# Version: 1.0.0
# Author: Robert Thomson - http://blog.corporatism.org/

from mako.lookup import TemplateLookup
from mako import exceptions
import settings

import sys
import os.path
from django.http import HttpResponse

# with thanks to Peter Hunt (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465427)
decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: \
                      decorator(func, *args, **kwargs)

@decorator_with_args
def mako(func, template=None):
    def MAKOIFY(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        if not res:
            res = {}
        if type(res) == dict:
            # use current_app/mako_templates/ as first search path.
            # the assumption is that the function's module is under current_app/
            d = os.path.join(
                  os.path.dirname(sys.modules[func.__module__].__file__),
                  "mako_templates/")
            lookup = TemplateLookup(directories=[d, 'mako_templates/'])
            res['request'] = request
            try:
                t = lookup.get_template(template)
                return HttpResponse(t.render(**res))
            except:
                if settings.DEBUG:
                    # display Mako's debug page on template error
                    return HttpResponse(exceptions.html_error_template()\
                                        .render(), status=500)
                raise
        else:
            # if not a dictionary or empty value, return literal result
            return res
    MAKOIFY.__name__ = func.__name__
    MAKOIFY.__doc__ = func.__doc__
    MAKOIFY.__dict__ = func.__dict__
    return MAKOIFY

"""Example usage:
from makodecorator import mako

@mako("index.mako")
def foo(request, id):
        return { "name" : "Robert Thomson" }
"""

More like this

  1. Subdirectory and subcontext include template tag with examples by t_rybik 5 years, 3 months ago
  2. A GET string modifier templatetag by cogat 6 years, 6 months ago
  3. Append paramaters to a GET querystring (template tag) by gregb 5 years, 11 months ago
  4. Renderer decorator by GaretJax 7 years, 7 months ago
  5. intergrate mako and genshi with django by huangyi 8 years, 3 months ago

Comments

bfrederi (on November 7, 2007):

What are the benefits of using Mako over the Django template system?

#

rmt (on December 10, 2008):

I quite like Jinja nowadays. :-)

#

Please login first before commenting.