Created
April 13, 2019 18:10
-
-
Save Den1al/5e64c8afa021c359dc0ea3c659eea2e9 to your computer and use it in GitHub Desktop.
Injecting the render_template function to sanic apps and templates
This file contains 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
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