Use render_async and a template env with jinja2
This commit is contained in:
parent
18829e648a
commit
c6aaa9b09c
|
@ -1,18 +1,27 @@
|
||||||
## To use this example:
|
# Render templates in a Flask like way from a "template" directory in the project
|
||||||
# curl -d '{"name": "John Doe"}' localhost:8000
|
|
||||||
|
|
||||||
from sanic import Sanic
|
from sanic import Sanic
|
||||||
from sanic import response
|
from sanic import response
|
||||||
from jinja2 import Template
|
from jinja2 import Evironment, PackageLoader, select_autoescape
|
||||||
|
|
||||||
template = Template('Hello {{ name }}!')
|
|
||||||
|
|
||||||
app = Sanic(__name__)
|
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('/')
|
@app.route('/')
|
||||||
async def test(request):
|
async def test(request):
|
||||||
data = request.json
|
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)
|
app.run(host="0.0.0.0", port=8080, debug=True)
|
Loading…
Reference in New Issue
Block a user