Skip to content

Instantly share code, notes, and snippets.

@Den1al
Created April 13, 2019 18:10
Show Gist options
  • Save Den1al/5e64c8afa021c359dc0ea3c659eea2e9 to your computer and use it in GitHub Desktop.
Save Den1al/5e64c8afa021c359dc0ea3c659eea2e9 to your computer and use it in GitHub Desktop.
Injecting the render_template function to sanic apps and templates
from sanic import Sanic, Blueprint
from jinja2 import Environment, PackageLoader, select_autoescape
from sanic.response import html
def get_package_name():
return __name__.split('.')[0]
class InjectJinjaSupport(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.env = Environment(
loader=PackageLoader(get_package_name(), 'templates'),
autoescape=select_autoescape([
'html', 'xml', 'tpl'
])
)
def render_template(self, template, **kwargs):
return html(
self.env.get_template(template).render(
kwargs
)
)
class SanicWithJinja(InjectJinjaSupport, Sanic):
pass
class BlueprintWithJinja(InjectJinjaSupport, Blueprint):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment