- 用上下文处理器app_context_processor定义函数
- 获取session中保存的值
- 返回字典
- 在父模板中更新导航,插入登录状态判断代码。、
- 注意用{% ... %}表示指令。
- {{ }}表示变量
- 完成注销功能。
- 清除session
- 跳转
@app.context_processor
def mycontext():
usern=session.get('user')
if usern:
return {'username':username}
else:
return {}
<nav>
<img id="myOnOff" onclick="mySwitch()"
src="{{ url_for('static',filename='image/base.jpg') }}" width="30px">
<a href="{{ url_for('base') }}">首页</a>
<a href="{{ url_for('regist') }}">注册</a>
<a href="{{ url_for('login') }}">登录</a>
<a href="{{ url_for('wenda') }}">问答</a>
{% if username %}
<li style="float:right"><a href="#">{{ username }}</a></li>
<li style="float:right"><a href="#">注销</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 %}
</nav>
@app.route('/logout/')
def logout():
session.clear()
return redirect(url_for('base'))