# 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. """