Skip to content

Instantly share code, notes, and snippets.

@jhargis
Last active November 18, 2018 22:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jhargis/b1bf47bd03e83930e346 to your computer and use it in GitHub Desktop.
Save jhargis/b1bf47bd03e83930e346 to your computer and use it in GitHub Desktop.
using jinja2 with cherrypy - example
# -*- coding: utf-8 -*-
# http://docs.cherrypy.org/en/latest/advanced.html?highlight=jinja2#html-templating-support
import os.path
import cherrypy
class Root(object):
@cherrypy.expose
def index(self):
return {'msg': 'Hello world!'}
if __name__ == '__main__':
cherrypy.config.update({'server.socket_port': 8090})
# Register the Jinja2 plugin
from jinja2 import Environment, FileSystemLoader
from jinja2plugin import Jinja2TemplatePlugin
env = Environment(loader=FileSystemLoader('.'))
Jinja2TemplatePlugin(cherrypy.engine, env=env).subscribe()
# Register the Jinja2 tool
from jinja2tool import Jinja2Tool
cherrypy.tools.template = Jinja2Tool()
# We must disable the encode tool because it
# transforms our dictionary into a list which
# won't be consumed by the jinja2 tool
cherrypy.quickstart(Root(), '', {'/': {'tools.template.on': True,
'tools.template.template': 'index.html',
'tools.encode.on': False}})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
<title></title>
</head>
<body>
{{msg}}
</body>
</html>
# -*- coding: utf-8 -*-
import cherrypy
from cherrypy.process import plugins
__all__ = ['Jinja2TemplatePlugin']
class Jinja2TemplatePlugin(plugins.SimplePlugin):
"""A WSPBus plugin that manages Jinja2 templates"""
def __init__(self, bus, env):
plugins.SimplePlugin.__init__(self, bus)
self.env = env
def start(self):
"""
Called when the engine starts.
"""
self.bus.log('Setting up Jinja2 resources')
self.bus.subscribe("lookup-template", self.get_template)
def stop(self):
"""
Called when the engine stops.
"""
self.bus.log('Freeing up Jinja2 resources')
self.bus.unsubscribe("lookup-template", self.get_template)
self.env = None
def get_template(self, name):
"""
Returns Jinja2's template by name.
Used as follow:
>>> template = cherrypy.engine.publish('lookup-template', 'index.html').pop()
"""
return self.env.get_template(name)
# -*- coding: utf-8 -*-
import cherrypy
__all__ = ['Jinja2Tool']
class Jinja2Tool(cherrypy.Tool):
def __init__(self):
cherrypy.Tool.__init__(self, 'before_finalize',
self._render,
priority=10)
def _render(self, template=None, debug=False):
"""
Applied once your page handler has been called. It
looks up the template from the various template directories
defined in the Jinja2 plugin then renders it with
whatever dictionary the page handler returned.
"""
if cherrypy.response.status > 399:
return
# retrieve the data returned by the handler
data = cherrypy.response.body or {}
template = cherrypy.engine.publish("lookup-template", template).pop()
if template and isinstance(data, dict):
cherrypy.response.body = template.render(**data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment