'How can I use jinja2 in python sanic?
According to my search. There are two main views:
- Install and use the sanic_jinja2
- Just use the jinja2
But above two methods didn't work to me(Maybe it's my fault).
Could anyone give me some example code?
Solution 1:[1]
tool/tmp.py
from jinja2 import Environment, PackageLoader
from functools import wraps
from sanic.response import html
# print(__name__) # ??????
# ?package_path??templates????????(??tmp.py??)
env = Environment(loader=PackageLoader(__name__, package_path='../templates'), enable_async=True)
class Tmp:
@staticmethod
def template(template_name):
def warapper(func):
@wraps(func)
async def inner(request, *args, **kwargs):
temp = env.get_template(template_name)
context = await func(request, *args, **kwargs)
return html(await temp.render_async(context))
return inner
return warapper
app.py
from sanic import Sanic
from tool.tmp import Tmp
app = Sanic(__name__)
app.static("static", "./static")
# ???Tmp
br = Tmp()
@app.route('/dag/<br>/<status>', methods=["GET"])
@br.template('dag.html') # ????templates?????html??
async def search_branch(request, br, status):
_branch = br
_status = status
_time = request.args.get('time')
return {'request': request, '_branch': _branch, '_status': _status, "_time": _time}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ??? |
