render_templates
渲染模板
* 模板放在 templates 文件夾下
* 從 flask 中導入 render_templates 函數
* 在視圖函數中,使用render_templates,只須要寫模板 名稱.html ,不須要寫路徑
除非是在templates下在建立子目錄就須要把路徑補充,以templates爲根目錄
@app.route('/') def hello_world(): return render_template('index.html')
參數傳遞html
* 若是隻有一個或者少許參數,直接在 render_templates 函數中添加關鍵字參數便可。
* 若是有多個參數,能夠把全部的參數放在字典中,而後在 render_templates中使用「 **字典名 」 轉成關鍵參數傳遞進去。
* 在HTML模板中,若是使用一個變量讓後臺傳參,HTML的語法是 「 {{params}}」
* 在HTML模板中的訪問後臺的屬性或者字典,能夠經過 {{params.property}}的形式,或者{{params['property']}}web
@app.route('/') def index(): class Person(object): name = u'姚明' age = 22 p = Person() content = { 'username': u'霸氣的男人名字', 'gender': u'男', 'age': '20左右', 'person': p, 'websites': { 'baidu': 'www.baidu.com', 'taobao': 'www.taobao.com' } } return render_template('index.html', **content)
<body> 這裏就是HTML傳來的!! <p>用戶名: {{ username }}</p> <p>性別:{{ gender }}</p> <p>年齡:{{ age }}</p> <hr> <p>名字: {{ person.name }}</p> <p>年齡: {{ person.age }}</p> <hr> <p>百度: {{ websites['baidu'] }}</p> <p>淘寶: {{ websites['taobao'] }}</p> </body>