Skip to content

Instantly share code, notes, and snippets.

@j2labs
Created April 1, 2012 15:28
Show Gist options
  • Save j2labs/2276382 to your computer and use it in GitHub Desktop.
Save j2labs/2276382 to your computer and use it in GitHub Desktop.
Possible brubeck templating.py overhaul
from request_handling import WebMessageHandler
### Rendering Mixing
class TemplateRendering(WebMessageHandler):
def render_template(self, template_file,
_status_code=WebMessageHandler._SUCCESS_CODE,
**context):
body = self.application.render_template(template_file, **context or {})
self.set_body(body, status_code=_status_code)
return self.render()
def render_error(self, error_code):
return self.render_template('errors.html', _status_code=error_code,
**{'error_code': error_code})
### Mako templates
def load_mako_env(template_dir, *args, **kwargs):
"""Returns a function which loads a Mako templates environment.
"""
def loader():
from mako.lookup import TemplateLookup
if template_dir is not None:
return TemplateLookup(directories=[template_dir or '.'],
*args, **kwargs)
else:
return None
return loader
### Jinja2
def load_jinja2_env(template_dir, *args, **kwargs):
"""Returns a function that loads a jinja template environment. Uses a
closure to provide a namespace around module loading without loading
anything until the caller is ready.
"""
def loader():
from jinja2 import Environment, FileSystemLoader
if template_dir is not None:
return Environment(loader=FileSystemLoader(template_dir or '.'),
*args, **kwargs)
else:
return None
return loader
### Tornado
def load_tornado_env(template_dir, *args, **kwargs):
"""Returns a function that loads the Tornado template environment.
"""
def loader():
from tornado.template import Loader
if template_dir is not None:
return Loader(template_dir or '.', *args, **kwargs)
else:
return None
return loader
### Mustache
def load_mustache_env(template_dir, *args, **kwargs):
"""
Returns a function that loads a mustache template environment. Uses a
closure to provide a namespace around module loading without loading
anything until the caller is ready.
"""
def loader():
return MustacheEnvironment(template_dir)
return loader
class MustacheEnvironment(object):
"""
An environment to render mustache templates.
"""
def __init__(self, template_dirs):
import pystache
self.pystache = pystache
self.template_dirs = template_dirs
def render(self, template_file, context):
view = self.pystache.View(context=context)
view.template_name = template_file
view.template_path = self.template_dirs
return view.render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment