Login

Integrate Tenjin using a decorator

Author:
mwdiers
Posted:
May 5, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This provides basic Tenjin integration, using a decorator. Tenjin is a blazingly fast templating system, the fastest pure-python system available.

For usage and configuration, see the example in the code.

I modeled this after Robert Thomson's code for Mako integration.

 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# tenjindecorator.py
# License: None, public domain
# Version: 1.0.1
# Author: Martin Diers - http://www.lutherantheology.com
# based on the mako decorator by Robert Thomson - http://blog.corporatism.org/

from tenjin import Engine
from tenjin.helpers import escape, to_str
import sys
import os.path
from django.http import HttpResponse

# Modify these to your liking. See doc string for details.
CACHE = True
ENCODING = 'UTF8'
TEMPLATEDIR = 'tenjin_templates/'

# 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 tenjin(func, template=None, layout=None):
    def TENJINIFY(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        if not res:
            res = {}
        if type(res) == dict:
            # Locate templates in current_app/TEMPLATEDIR
            d = os.path.join(
                  os.path.dirname(sys.modules[func.__module__].__file__),
                  TEMPLATEDIR)
            res['request'] = request
            res['templatepath'] = d
            # tell the engine to use prefix and postfix for layout and template
            mytemplate = ':' + template if template else None
            mylayout = ':' + layout if layout else None
            engine = Engine(prefix=d, postfix='.pyhtml', layout=mylayout, encoding=ENCODING, cache=CACHE)
            return HttpResponse(engine.render(mytemplate, res))
        else:
            # if not a dictionary or empty value, return literal result
            return res
    TENJINIFY.__name__ = func.__name__
    TENJINIFY.__doc__ = func.__doc__
    TENJINIFY.__dict__ = func.__dict__
    return TENJINIFY

"""Example usage:
from tenjindecorator import tenjin
LAYOUT = 'mylayout'

@tenjin("mytemplate", LAYOUT)
def foo(request, id):
    today = '' + datetime.date.today()
    return { 'title': 'My Page Title', 'today' : today }
        

NOTES
If layout is not specified, no layout will be used.
All templates must be stored in 'current_app/TEMPLATEDIR'. See below.
All templates and layouts must be have a .pyhtml extention.
Pass the template and layout names without a path or extension.
Your view function must return a dictionary, which will be passed
intact to Tenjin as the template context.
The variable 'templatepath' is automatically added to the template context to make
it easier to include() other Tenjin templates / embed JS / CSS, etc.

Change the default ENCODING as necessary. Set it to None to return templates
as str. Any other value returns unicode.

Set TEMPLATEDIR to the name of the template directory. This directory needs to
be located within the current app's directory. The default is 'tenjin_templates/'
Remember to include the trailing "/".

Tenjin templates will be compiled to python byte code, and cached in the
current_app/TEMPLATEDIR directory. If your web server does not have
write access to this directory, you will need to pre-compile these 
templates to retain the speed of Tenjin. Otherwise, you can disable
caching by changing the CACHE constant to False.
"""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.