Python版本:Python-3.9.4
在线安装Jinja2:
pip3 install sanic-jinja2
离线安装Jinja2:
sanic_jinja2-0.9.1-py3-none-any.whl
Jinja2-2.11.3-py2.py3-none-any.whl
MarkupSafe-1.1.1-cp39-cp39-win_amd64.whl
修改模块配置modules目录下__init__.py
# -*- coding: utf-8 -*-
import sys
from jinja2 import Environment, FileSystemLoader, select_autoescape
from sanic.response import html
"""
所有蓝图name必须添加的地方
"""
__all__ = [
"user",
"taobaoke"
]
# 配置模板路径
template_paths = []
for module_name in __all__:
template_paths.append('./static/templates/' + module_name)
# 配置同步环境
env_sync = Environment(loader=FileSystemLoader(template_paths),
autoescape=select_autoescape(['html', 'xml', 'tpl']),
enable_async=False)
enable_async_flag = sys.version_info >= (3, 6)
# 配置异步环境
env_async = Environment(loader=FileSystemLoader(template_paths),
autoescape=select_autoescape(['html', 'xml', 'tpl']),
enable_async=enable_async_flag)
# 同步模板渲染
def template_render_sync(template_file, **kwargs):
template = env_sync.get_template(template_file)
rendered_template = template.render(kwargs)
return html(rendered_template)
# 异步模板渲染
async def template_render_async(template_file, **kwargs):
template = env_async.get_template(template_file)
rendered_template = await template.render_async(kwargs)
return html(rendered_template)
Service代码