1、使用Flask-Bootstrap集成Twitter Bootstrap
目录结构
安装flask-bootstrap
Flask-Bootstrap从falsk_bootstrap命名空间中导入,然后把程序实例传入构造方法中进行初始化
Jinja2中的extends指令从Flask-Bootstrap中导入bootstrap/base.html;从而实现模板继承。Flask-bootstrap中的基摸板提供了一个网页框架,引入了Bootstrap中所有的css和JavaScript文件
基模板中定义了可在衍生模板中重定义的块。block和endblock指令定义的块中内容可添加到基模板中
2、重写基页并添加自定义错误页
改写后的目录结构
添加基页base.html
{% extends "bootstrap/base.html" %} {% block title %}Flasky{% endblock %} {% block navbar %} <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Flask</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> </ul> </div> </div> </div> {% endblock %} {% block content %} <div class="container"> <div class="page-header"> {% block page_content %}{% endblock %} </div> </div> {% endblock %}
基于base.html改写user.html
{% extends "base.html" %} {% block title %}Flasky{% endblock %} { % block page_content %} <div class="page-header"> <h1>Hello, {{ name }}!</h1> </div> {% endblock %}
基于base.html添加自定义错误页
404.html
{% extends "base.html" %} {% block tittle %}Flasky - Page Not Found{% endblock %} {% block page_content %} <div class="page-header"> <h1>Not Found</h1> </div> {% endblock %}
500.html
{% extends "base.html" %} {% block tittle %}Flasky - Internal Server Error{% endblock %} {% block page_content %} <div class="page-header"> <h1>Internal Server Error</h1> </div> {% endblock %}
在hello.py中加入404,500的视图函数
from flask import Flask,request,make_response,redirect,render_template from flask_bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) @app.route('/') def index(): return render_template('index.html') @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) @app.route('/user/<id>') def get_user(id): user = load_user(id) if not user: abort(404) return '<h1>Hello, %s</h1>' % user.name if __name__ == '__main__': bootstrap.run()
网页显示