加载静态文件,父模板的继承和扩展

  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. 首页、登录页、注册页都按上述步骤改写
    首页:
    <!
    DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %}{% endblock %} 首页</title> {# <link type="text/css" rel="stylesheet" href="{{ url_for('static',filename='css/jianshu.css') }}">#} <link type="text/css" rel="stylesheet" href="{{ url_for('static',filename='css/base.css') }}"> <script src="{{ url_for('static',filename='js/nightmode.js') }}"> </script> {% block head %}{% endblock %} </head> <body id="mybody"> <nav class="navbody"> <img src="https://p1.ssl.qhmsg.com/dr/270_500_/t01745b3fd4078d5a9e.jpg?size=512x512" height="100" width="100"> <a href="http://www.jianshu.com/"></a> <input type="text" name="search"> <button type="submit">搜索</button> <a href="{{ url_for('jianshu') }}">首页</a> <a href="{{ url_for('login') }}">登陆</a> <a href="{{ url_for('enroll') }}">注册</a> <img src="{{ url_for('static',filename='img/dog.png') }}" alt="" height="100"> <img id="myonoff" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" width="40"> </nav> {% block main %}{% endblock %}
    登录页面:
    {% extends 'jianshu.html'%} {% block title %}登录{% endblock %} {% block head %}
    <link type="text/css" rel="stylesheet" href="{{ url_for('static',filename='css/login.css') }}"> <script src="{{ url_for('static',filename='js/login.js') }}"></script> {% endblock %} {% block main %} <div class="box"> <h2>登陆</h2> <div class="input_box"> <input id="uname" type="text" placeholder="请输入用户名"> </div> <div class="input_box"> <input id="upass" type="password" placeholder="请输入密码"> </div> <div id="error_box"><br></div> <div class="input_box"> <button onclick="fnlogin()">登陆</button> </div> </div> {% endblock %}
    注册页面:
    {% extends 'jianshu.html' %} {% block title %}注册{% endblock %} {% block head %}
    <link type="text/css" rel="stylesheet" href="{{ url_for('static',filename='css/login.css') }}"> <script src="{{ url_for('static',filename='js/enroll.js') }}"></script> {% endblock %} {% block main %} <div class="box"> <h2>注册</h2> <div class="input_box"> <input id="uname" type="text" placeholder="请输入昵称"> </div> <div class="input_box"> <input id="upass" type="password" placeholder="请输入密码"> </div> <div class="input_box"> <input id="upass1" type="password" placeholder="请再次输入密码"> </div> <div id="error_box"><br></div> <div class="input_box"> <button onclick="tnlogin()">注册</button> </div> </div> {% endblock %}

原文地址:https://www.cnblogs.com/lintingting/p/7780894.html