天天看点

sanic(3):调用templates

经过上文,我们已经能输出hello这个单词。这说明服务已经成功响应。这里,我们将使用jinja2来进行html的渲染。

jinja2怎么用,已经超出了本文范围,所以本文只讲后端的调用。

创建Jinja2服务

回忆一下,在

app.py

中,已经定义了jinja2的服务,代码如下:

...
@app.listener('before_server_start')
async def setup_db_redis(app, loop):
    ......
    templates_path = os.path.join(os.getcwd(), 'templates')
    app.template_env = Environment(
        loader=FileSystemLoader(templates_path),
        autoescape=select_autoescape(['html', 'xml']),
        enable_async=False
    )           

复制

这里我使用了

FileSystemLoader

做为loader,避免乱七八糟的问题。

后端渲染

在我写完这些代码之时,前端的哥们已经把html文件写好了。所以项目中多出了这样的结构:

├── templates
│   └── web
│       ├── index.html           

复制

渲染示例

index.py

文件:

@games_bp.route('/index', methods=['GET'])
async def index(request):
    logging.info("index run")
    online_items = await QB_GAMES.where(eq(online=1)).order_by_desc('id').run()
    template = request.app.template_env.get_template('web/index.html')
    html_content = template.render(online_items=online_items)
    return html(html_content)           

复制

1.从数据库中获取了onlien_items(当然你也可以从其它地方获取数据)。

2.通过

request.app

获取到app对象。jinja2的templates做为一个属性被保存到了app中。

3.使用jinja函数

get_template

获取templates对象。

4.使用调用render方法渲染出html

5.用sanic的

html()

方法返回这个response对象。