Flask--模板渲染和參數傳遞


#############Python代碼#########################

'''

渲染模板:
1、靜態頁面模板放在templates文件夾中
2、需要導入render_template
3、視圖函數中使用render_template函數渲染模板本例中使用的是return render_template('index.html', **context)
4、傳多個參數的時候可以使用字典的形式如本例中的context={}
5、html代碼中參數使用{{}}進行引用 本例中是
<p>用戶名:{{ username }}</p>
<p>年齡:{{ age }}</p>
6、傳參數類,字典 請看本例中的person類以及context中的wwwurl字典

'''

from flask import Flask,render_template
import time
app = Flask(__name__)


@app.route('/')
def index():
class Person(object):
Email = 'XXX@XXX.com';
time = time.time();

dell=Person()

context={
'username':"王亞鋒",
'age': "18",
'gender': "男",
'flag': "王者",
'hero': "猴子",
'person':dell,
'wwwurl':{
'baidu':'www.baidu.com',
'google':'www.google.com'
}
}
return render_template('index.html', **context)


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

 

############index.html############################

<!DOCTYPE html>
<html lang="utf-8">
<head>
<meta charset="UTF-8">
<title>王亞鋒</title>
</head>
<body>
這是一個簡單的頁面,falsk勾搭html
<p style="color:#FF00FF">用戶名:{{ username }}</p>
<p>年齡:{{ age }}</p>
<p style="color:#7B68EE">性別:{{ gender }}</p>
<p>等級:{{ flag }}</p>
<p style="color:#FF00FF">英雄:{{ hero }}</p>
<hr>
<!--引用類中的參數-->
<p style="color:#7B68EE"> 申請郵箱:{{person.Email}}</p>
<p style="color:#FF00FF">申請時間:{{person.time }}</p>
<hr>
<!--引用wwwurl字典中的參數,有兩種形式-->
<p style="color:#7B68EE">百度:{{wwwurl.baidu}}</p>
<p style="color:#FF00FF">谷歌:{{wwwurl['google'] }}</p>
</body>
</html>

=================頁面結果======================================

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>你好</title>
</head>
<body>
<h1>{{ content }}</h1>
</body>
</html>

 

 

 

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM