04-使用 Jinja2 模板

  • 阅读: 396
  • 更新: 2022-04-26

Jinja2 是一个现代的,设计者友好的,仿照 Django 模板的 Python 模板语言。
官网地址:http://docs.jinkan.org/docs/jinja2/index.html

示例:

1
2
3
4
5
6
<title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>

1. 安装 Jinja2

1
pip install Jinja2

2. 使用

咱们先新建一个 apps 目录,然后在 apps 目录中新建一个 templates 目录;用于存放 jinja2 模板文件

新建一个 apps/templates/index.html 文件:

1
2
3
{% for i in range(10) %}
  <h1>{{ msg }}</h1>
{% endfor %}

然后修改一下 server.py 文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from sanic import Sanic
from sanic import response
from jinja2 import Environment, PackageLoader

app = Sanic('MyAPP')
jinja2 = Environment(loader=PackageLoader('apps', 'templates'))


@app.get('/')
async def hello_world(request):
    template = jinja2.get_template('index.html')
    context = {
        'msg': 'Hello, world.'
    }
    html = template.render(**context)
    return response.html(html)


if __name__ == '__main__':
    app.run(debug=True, auto_reload=True)

重点是这几个:

  1. jinja2 模板的引入

    1
    2
    3
    jinja2 = Environment(loader=PackageLoader('apps', 'templates'))
    # ...
    template = jinja2.get_template('index.html')
    
  2. 模板变量的传入

    1
    html = template.render(**context)
    
  3. 以 html 格式进行响应

    1
    return response.html(html)
    

此时再次访问 http://127.0.0.1:8000 就能看到 10 个比之前更大的 Hello, world.


=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1