基於hi-nginx的web開發(python篇)——使用jinja2模板引擎,hi-nginxjinja2

來源:互聯網
上載者:User

基於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,所以,盡情中文吧!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.