Skip to content

安装jinja2-sanic

python
pip3 install jinja2-sanic

快速开始

python
from sanic import Sanic
from sanic.views import HTTPMethodView
from sanic.exceptions import ServerError

app = Sanic("sanic_jinja2_render")

# Setup jinja2 environment
template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>"
jinja2_sanic.setup(
    app,
    loader=jinja2.DictLoader(
        {
            "templates.jinja2": template
        }
    )
)
# or 
jinja2_sanic.setup(app, filters=None, loader=jinja2.FileSystemLoader('/project/templates'))

# Usage in function based web handlers
@app.route("/")
@jinja2_sanic.template("templates.jinja2")
async def func(request):
    return {
        "Player": "CR7",
        "Category": "Soccer",
    }

# Usage in class-based views
class SimpleView(HTTPMethodView):

    @jinja2_sanic.template("templates.jinja2")
    async def get(self, request):
        return {
            "Player": "CR7",
            "Category": "Soccer",
        }

# register class based view routes
app.add_route(SimpleView.as_view(), "/")

# Start Server
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

更多用法

http://jinja.pocoo.org/docs/2.10/api