Flask 模板(一),flask模板

來源:互聯網
上載者:User

Flask 模板(一),flask模板

使用模板有助於將商務邏輯與表現邏輯分開,更易於維護。模板是已經建立的網頁代碼,其中部分動態資料需要在請求的上下文中用具體值替換。

flask中使用了Jinja2模板引擎,儲存在templates檔案夾中。

templates/index.html
<h1>Hello World!</h1>

使用 {{ name }} 佔位

templates/user.html<h1>Hello, {{ name }}!</h1>

 

模板的渲染

模板的渲染即用真實值取代模板中的佔位變數的過程。

from flask import Flask,render_template@app.route('/')def index():    return render_template('index.html',name=name)

變數可以從列表、字典和對象擷取。

<p>A value from a dict:{{ mydict['key'] }}</p><p>A value from a list:{{ mylist[3] }}</p><p>A value from a list with a variable index:{{ mylist[intvar] }}</p><p>A value from a object's method :{{ myobj.mymethod() }}</p>

使用過濾器修改變數:

{{ name|capitalize }}

常用過濾器:

過濾器名 說明
safe 渲染時不轉義
capitalize 首字母大寫,其他小寫
lower 小寫
upper 大寫
title 每個單字首大寫
trim 去掉首尾空格
striptags 把值中所有html標籤刪掉

 

 

 

 

 

 

 

 

控制結構

 

{% if user %}    Hello,{{ user }}{% else %}    Hello,Stranger!{% endif %}

 

<ul>    {% for comment in comments %}        <li>{{ comment }}</li>    {% endfor %}</ul>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.