用上下文处理器app_context_processor定义函数
- 获取session中保存的值
- 返回字典
@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 logintitle %}{% endblock %} {% block registertitle %}{% endblock %} {% block wendatitle %}{% endblock %} </title> <script> function mySwitch() { var oBody = document.getElementById("myBody"); var oOnoff = document.getElementById("myOnOff"); if (oOnoff.src.match("bulbon")) { oOnoff.src = "http://www.runoob.com/images/pic_bulboff.gif"; oBody.style.background = "black"; oBody.style.color = "yellow"; } else { oOnoff.src = "http://www.runoob.com/images/pic_bulbon.gif"; oBody.style.background = "lightcyan"; oBody.style.color = "black"; } } </script> <link rel="stylesheet" type="text/css" href="../static/css/moban.css"> {% block loginhead %}{% endblock %} {% block registerhead %}{% endblock %} {% block wendahead %}{% endblock %} </head> <body id="myBody" style=" padding: 0px; line-height: 1.8; color: rgb(128, 0, 0);">"> <nav> <img src="{{ url_for('static',filename='image/gzsxy.png') }}" alt="" width="20px"> <script> document.write(Date()) </script> <br> <a href="{{ url_for('moban') }}">首页</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 %} <a href="{{ url_for('wenda') }}">问答</a> <input type="text" placeholder="请输入关键字"> <button type="submit">搜索</button> </nav> <p>{{ username }}context</p> {% block loginbody %}{% endblock %} {% block registerbody %}{% endblock %} {% block wendabody %}{% endblock %} </body> </html>
完成注销功能。
- 清除session
- 跳转
@app.route('/logout/') def logout(): session.clear() return redirect(url_for('moban'))