登录之后更新导航
- 用上下文处理器app_context_processor定义函数
- 获取session中保存的值
- 返回字典
@app.context_processor def mycontext(): usern = session.get('user') if usern: return {'username':usern} else: return{}
- 在父模板中更新导航,插入登录状态判断代码。、
- 注意用{% ... %}表示指令。
- {{ }}表示变量
<ul> <li><img class="ico" src="../static/img/ico.jpg" alt="" style="margin-top: 12px"></li> <li><a href="{{ url_for('index') }}">首页</a></li> <li><input type="text" class="form-control" placeholder="Search" style="margin-top: 8px" ></li> <li><button type="submit" class="btn btn-default" style="margin-top: 8px">搜索</button></li> <li><a href="{{ url_for('question') }}">提问</a></li> {% if username %} <li style="float:right"><a href="#">{{ username }}</a></li> <li style="float:right"><a href="{{ url_for('logout') }}">注销</a></li> {% else %} <li style="float:right"><a href="{{ url_for('login') }}">登陆</a></li> <li style="float:right"><a href="{{ url_for('regist') }}">注册</a></li> {% endif %} <li style="float: right"> <img id="myOnOff" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" class="bulb"></li> </ul>
- 完成注销功能。
- 清除session
- 跳转
@app.route('/logout/') def logout(): session.clear() return redirect(url_for('index'))
运行截图:
登录:
注销: