sanic用jinja2作模版引擎(宏的引用)

2019-02-27  本文已影响0人  hugoren

web解释常用的模版有

sanic目前支持模版引擎

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
上一篇下一篇

猜你喜欢

热点阅读