天天看点

python 3.5 sanic web framework template with jinga2

安装模板引擎Jinja2

MarkupSafe-0.23.tar.gz

Jinja2-2.8.tar.gz

2.配置模板引擎到blueprint

/home/webapp

     |-- main.py

     |-- my_blueprint.py

     templates

        |-- index.html

1).main.py

from sanic import Sanic

from my_blueprint import bp

app = Sanic(__name__)

app.blueprint(bp)

app.run(host='0.0.0.0', port=8000, debug=True)

2).my_blueprint.py

# more my_blueprint.py 

from sanic.response import json, text, html

from sanic import Blueprint

from jinja2 import Environment, PackageLoader

env = Environment(loader=PackageLoader('my_blueprint', 'templates'))

bp = Blueprint('my_blueprint')

@bp.route('/')

async def bp_root(request):

    template = env.get_template('index.html')

    content=template.render(title='Sanic',people='David')

    return html(content)

3).index.html

# more index.html 

<!doctype html>

<title>` title `</title>

<div class=page>

  <h1>hello, ` people `</h1>

</div>

3.运行测试

运行服务

/home/webapp/目录下

[root@localhost webapp]# 

[root@localhost webapp]# python main.py 

<a href="http://s3.51cto.com/wyfs02/M01/8B/6F/wKiom1hOUIqC4FskAAKowjhQOjU050.jpg-wh_500x0-wm_3-wmp_4-s_2399249024.jpg" target="_blank"></a>

<a href="http://s5.51cto.com/wyfs02/M01/8B/6C/wKioL1hOTwTALBGEAABdymxWWGQ875.jpg-wh_500x0-wm_3-wmp_4-s_1871579911.jpg" target="_blank"></a>

本文转自 pgmia 51CTO博客,原文链接:http://blog.51cto.com/heyiyi/1881950