From c6aaa9b09c58cc964c5ec4877b43d014d1ae4566 Mon Sep 17 00:00:00 2001 From: Tom Haines Date: Sun, 16 Apr 2017 13:50:07 +0100 Subject: [PATCH] Use render_async and a template env with jinja2 --- examples/jinja_example.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/examples/jinja_example.py b/examples/jinja_example.py index ba8b3354..cf517030 100644 --- a/examples/jinja_example.py +++ b/examples/jinja_example.py @@ -1,18 +1,27 @@ -## To use this example: -# curl -d '{"name": "John Doe"}' localhost:8000 +# Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response -from jinja2 import Template - -template = Template('Hello {{ name }}!') +from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) +# Load the template environment with async support +template_env = Environment( + loader=jinja2.PackageLoader('yourapplication', 'templates'), + autoescape=jinja2.select_autoescape(['html', 'xml']), + enable_async=True +) + +# Load the template from file +template = template_env.get_template("example_template.html") + + @app.route('/') async def test(request): data = request.json - return response.html(template.render(**data)) + rendered_template = await template.render_async(**data) + return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True) \ No newline at end of file