在Web框架中,通过模板试了了业务逻辑和表现逻辑的分离。模板是一个包含响应文本的文件,其中包含占位变量表示动态的部分,其具体值只有在请求的上下文中才能知道。使用真实值替换变量,再返回最终得到的响应字符串,这一过程称之为渲染。为了渲染模板,Flask使用Jinja2模板引擎。
基本用法
1 2 3 4 5 from flask import render_template@app.route('/user/<name>') def user (name) : return render_template('user.html' , name=name)
1 2 3 4 5 6 <p > A value from a dictionary: {{ mydict['key'] }}.</p > <p > A value from a list: {{ mylist[3] }}.</p > <p > A value from a list, with a variable index: {{ mylist[myintvar] }}.</p > <p > A value from an object's method: {{ myobj.somemethod() }}.</p > Hello, {{ name|capitalize }}
常见过滤器:safe
,trim
,striptags
1 2 3 4 5 {% if user %} Hello, {{ user }}! {% else %} Hello, Stranger! {% endif %}
1 2 3 4 5 <ul > {% for comment in comments %} <li > {{ comment }}</li > {% endfor %} </ul >
1 2 3 4 5 6 7 8 9 {% macro render_comment(comment) %} <li > {{ comment }}</li > {% endmacro %} <ul > {% for comment in comments %} {{ render_comment(comment) }} {% endfor %} </ul >
1 2 3 4 5 6 {% import 'macros.html' as macros %} <ul > {% for comment in comments %} {{ macros.render_comment(comment) }} {% endfor %} </ul >
1 {% include 'common.html' %}
1 2 3 4 5 6 7 8 9 10 11 12 <html > <head > {% block head %} <title > {% block title %}{% endblock %} - My Application</title > {% endblock %} </head > <body > {% block body %} {% endblock %} </body > </html >
1 2 3 4 5 6 7 8 9 10 {% extends "base.html" %} {% block title %}Index{% endblock %} {% block head %} {{ super() }} <style > </style > {% endblock %} {% block body %} <h1 > Hello, World!</h1 > {% endblock %}
1 2 3 4 5 url_for('index' , _external=True ) url_for('user' , name='john' , _external=True ) url_for('index' , page=2 ) url_for('static' , filename='css/style.css' , _external=True )
Flask-Bootstrap 1 $ pip install Flask-Bootstrap
1 2 3 4 from flask.ext.bootstrap import bootstrapbootstrap = bootstrap(app)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 {% extends "bootstrap/base.html" %} {% block title %}Flasky{% endblock %} {% block nav %} <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 > </div > <div class ="navbar-brand" href ="/" > Flask</a > <ul class ="navbar-collapse collapse" > <li > <a href ="/" > Home</a > </li > </ul > </div > </div > </div > {% endblock %} {% block content %} <div class ="container" > <div class ="page-header" > <h1 > Hello, {{ name }}!</h1 > </div > </div > {% endblock %}
1 2 3 4 {% block scripts %} {{ super() }} <script type ="text/javascript" src ="my-script.js" > </script > {% endblock %}
自定义错误页面 1 2 3 @app.errorhandler(404) def page_not_found (e) : return render_template('404.html' ), 404