1. 程式人生 > >加載靜態文件,父模板的繼承和擴展

加載靜態文件,父模板的繼承和擴展

ges perf bmi cli wid spa pre __main__ oal


  1. 用url_for加載靜態文件
    1. <script src="{{ url_for(‘static‘,filename=‘js/login.js‘) }}"></script>
    2. flask 從static文件夾開始尋找
    3. 可用於加載css, js, image文件
  2. 繼承和擴展
    1. 把一些公共的代碼放在父模板中,避免每個模板寫同樣的內容。base.html
    2. 子模板繼承父模板
      1. {% extends ‘base.html’ %}
    3. 父模板提前定義好子模板可以實現一些自己需求的位置及名稱。block
      1. <title>{% block title %}{% endblock %}-MIS問答平臺</title>
      2. {% block head %}{% endblock %}
      3. {% block main %}{% endblock %}
    4. 子模板中寫代碼實現自己的需求。block
      1. {% block title %}登錄{% endblock %}
  3. 首頁、登錄頁、註冊頁都按上述步驟改寫。

untitled

from flask import Flask,render_template

app = Flask(__name__)


@app.route(/)
def base():
    return render_template(base.html)

@app.route(/load/
) def load(): return render_template(load.html) @app.route(/register/) def register(): return render_template(register.html) if __name__ == __main__: app.run()

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        {
% block title %}{% endblock %} 首頁 </title> <link rel="stylesheet" type="text/css" href="{{ url_for(‘static‘,filename=‘css/base.css‘) }}"> <script src="{{ url_for(‘static‘,filename=‘js/base.js‘) }}"></script> {% block head %} {% endblock %} </head> <body id="myBody"> <nav> <img src="http://p1.img.cctvpic.com/photoAlbum/page/performance/img/2013/8/27/1377583188891_732.jpg" width="800px"height="150px"><br> <img id="myOnOff" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" width="25px"> <a href="http://www.sesamestreetchina.com.cn/">首頁</a> <input type="text"name="search"> <button type="submit">搜索</button> <a href="{{ url_for(‘login‘) }}">登錄</a> <a href="{{ url_for(‘regist‘) }}">註冊</a> <img src="{{ url_for(‘static‘,filename=‘image/86x97sZ11K4.jpg‘) }}" alt="" width="50px"> </nav> <div class="area"> {% block main %} {% endblock %} </div> <footer> <div class="footer_box"> Copyright@2017 個人版權,版權所有  作者:楊碧茜</div> </footer> </body> </html>

技術分享

技術分享

技術分享

加載靜態文件,父模板的繼承和擴展