登录之后更新导航

  1. 用上下文处理器app_context_processor定义函数
    1. 获取session中保存的值
    2. 返回字典
  2. 在父模板中更新导航,插入登录状态判断代码。、
    1. 注意用{% ... %}表示指令。
    2. {{ }}表示变量
  3. 完成注销功能。
    1. 清除session
    2. 跳转
      @app.context_processor
      def mycontext():
          username = session.get('user')
          if username:
              return {'username':username}
          else:
              return {}
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %}简书% endblock %}</title>
      
      {% block head %}{% endblock %}
      
      </head>
      <body class="box">
      
      <nav>
      
          <a class="logo" href="http://www.jianshu.com/">
              <img src="http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png" alt="Logo"></a>
          <a href="http://127.0.0.1:5000/base2">首页</a>
      
            {% if username %}
            <a href="#">{{ username }}</a>
            <a href="{{ url_for('logout') }}">注销</a>
            {% else %}
            <a href="{{ url_for('login') }}">登陆</a>
            <a href="{{ url_for('register') }}">注册</a>
            {% endif %}
      
          <input type="text"name="search">
          <button type="submit">搜索</button>
      
      </nav>
      
      <hr>
      
      {% block main %}{% endblock %}
      </body>
      </html>
      @app.route('/logout/')
      def logout():
          session.clear()
          return redirect(url_for('index'))

       

posted on 2017-11-24 21:30  045钟嘉丽  阅读(128)  评论(0编辑  收藏  举报

导航