Last active
December 17, 2015 19:19
-
-
Save wilburding/5660070 to your computer and use it in GitHub Desktop.
a simple jinja template integretion to tornado
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#fileencoding=utf-8 | |
from jinja2 import Environment | |
from jinja2 import FileSystemLoader | |
import datetime | |
def guess_autoescape(template_name): | |
if template_name is None or '.' not in template_name: | |
return False | |
ext = template_name.rsplit('.', 1)[1] | |
return ext in ('html', 'htm', 'xml') | |
def _ts_format(ts, format="%X %x"): | |
dt = datetime.datetime.fromtimestamp(ts) | |
return dt.strftime(format) | |
class JinjaLoader(object): | |
def __init__(self, root_path, **kwargs): | |
super(JinjaLoader, self).__init__(**kwargs) | |
self.env = Environment(loader=FileSystemLoader(root_path), | |
autoescape=guess_autoescape, | |
extensions=['jinja2.ext.autoescape'], | |
trim_blocks=True, | |
lstrip_blocks=True,) | |
additional_globals = { | |
'ord': ord, | |
'chr': chr, | |
'unichr': unichr, | |
} | |
self.env.globals.update(additional_globals) | |
self.env.filters['ts_format'] = _ts_format | |
def load(self, name, parent_path=None): | |
return JinjaTemplate(self.env.get_template(name)) | |
def reset(self): | |
'''Reset the cache of compiled templates, required | |
in debug mode. | |
''' | |
self.env.cache.clear() | |
class JinjaTemplate(object): | |
def __init__(self, template): | |
self.template = template | |
def generate(self, **kwargs): | |
# jinja uses unicode internally but tornado uses utf string | |
return self.template.render(**kwargs).encode('utf-8') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment