web解释常用的模版有
- django 自带的template
- jinja2比第一个要强大
- mako比jinja2灵活
sanic目前支持模版引擎
- jinja2
- sanic-jinja
- sanic-mako
- Sanic-WTF: Sanic-WTF makes using WTForms with Sanic and CSRF (Cross-Site Request Forgery) protection a little bit easier.
- Jinja2: Support for Jinja2 template.
- jinja2-sanic: a jinja2 template renderer for Sanic.(Documentation)
jinja2宏的使用
basic.html
{% macro static_file(type, filename_or_url, local=true) %}
{% if local %}
{% set filename_or_url = url_for('static', filename=filename_or_url) %}
{% endif %}
{% if type == 'css' %}
<link rel="stylesheet" href="{{ filename_or_url }}" type="text/css">
{% elif type == 'js' %}
<script type="text/css" src="{{ filename_or_url }}"></script>
{% elif type=='icon' %}
<link rel='icon' href='{{ filename_or_url }}'>
{% endif %}
{% endmacro %}
页面引用
在同页面中直接引用
{{ static_file('js', "static/js/adminlte.js")}}
在不同页面中引用
{% import 'basic.html' as ui%}
{{ ui.static_file('css', "static/css/bootstrap.min.css")}}
这里使用sanic-jinja2
sanic-jinja2
响应页面
工程结构
image.png
代码引用
from sanic import Sanic
from sanic_session import Session
from sanic_jinja2 import SanicJinja2
app = Sanic()
Session(app)
jinja = SanicJinja2(app)
#
# Specify the package name, if templates/ dir is inside module
# jinja = SanicJinja2(app, pkg_name='sanicapp')
# or use customized templates path
# jinja = SanicJinja2(app, pkg_name='sanicapp', pkg_path='other/templates')
# or setup later
# jinja = SanicJinja2()
# jinja.init_app(app)
@app.route('/')
@jinja.template('index.html') # decorator method is staticmethod
处理静态资源
app = Sanic(__name__)
app.static('/static', './templates/')
测试
image.png
网友评论