基於hi-nginx的web開發(python篇)——使用jinja2模板引擎,hi-nginxjinja2
模板引擎的使用在web開發中是不可避免和必要的。hi.py架構使用jinja2作為模板引擎。
為了使用hi.py提供的jinja2引擎,首先需要引入它:
from hi import hi,template
然後就是使用它:
1 @app.route(r'^/template/(?P<name>\w+)/(?P<age>\d+)/?$',['GET'])2 def tpl(req,res,param):3 param['title']='jinja2 測試'4 tpl_engine = template(os.path.join(os.getcwd(),'python/templates'))5 res.content(tpl_engine.file_render('b.html',param))6 res.status(200)
建立template執行個體需要一個參數,它指定引擎搜尋模板檔案的目錄,在上面的代碼中就是hi-nginx安裝目錄下的python/templates檔案夾。
然後準備資料,資料使用dict來收集,使用file_render方法通過指定模板檔案和資料dict來輸出字串內容。
如果使用的不是模板檔案,而是模板字串,那就使用string_render方法,它的第一個參數指的是字串模板。
在上面的例子中,模板檔案b.html內容如下:
1 {% extends 'a.html' %}2 {% block body %}3 {{ super() }}4 繼承5 {{ name }} is {{ age }} years old.6 {% endblock %}
其中使用了jinja2中的模板繼承功能,見第一行。因此,還有個模板檔案a.html:
<html> <head><title>{{ title }}</title></head> <body>{% block body %} <p>Hello:{{ name }},you are {{ age }} years old.</p> <p>載入器負責從諸如檔案系統的資源載入模板</p> {% endblock %} </body></html>
在本例中,中文內容已經出現。因此需要使用utf-8編碼。hi-nginx已經全面支援python3,所以,盡情中文吧!