Mako support as decorator

 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 4 years, 1 month ago
  2. A GET string modifier templatetag by cogat 5 years, 4 months ago
  3. Append paramaters to a GET querystring (template tag) by gregb 4 years, 9 months ago
  4. Renderer decorator by GaretJax 6 years, 4 months ago
  5. intergrate mako and genshi with django by huangyi 7 years, 1 month 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. :-)

#

(Forgotten your password?)