概念剖析
- (Model View Control) 表現(xiàn)層、業(yè)務(wù)層與模型層分離機(jī)制脯颜,而模板用來管理表現(xiàn)層。
- 模板是一個(gè)包含相應(yīng)文本的文件,其中的動(dòng)態(tài)部分用占位量表示,占位量的具體值只有在請求上下文中才知道谁不。使用真實(shí)值替換相應(yīng)字符痰憎。
jinja2初試
- 創(chuàng)建模板文件夾
templates
,創(chuàng)建模板文件index.html
,user.html
-
index.html
輸入<h1> hello world!</h1>
-
index.html
輸入<h1> hello {{ name }}!</h1>
-
hello.py
文件
from flask import Flask, render_template
from flask_script import Manager
app = Flask(__name__)
manager = Manager(app)
# 路由的基本用例
@app.route('/')
def index():
return render_template( 'index.html' )
# 動(dòng)態(tài)路由的基本用例
@app.route('/user/<name>')
def user(name):
## 使用 jinja2 模板引擎,傳入鍵值對珍策,關(guān)鍵字參數(shù)
return render_template('user.html', name=name)
if __name__ == '__main__':
manager.run()
- 提交到倉庫
git add hello.py, readme.md templates
,git commit -m "jinja2 first demo"
- 創(chuàng)建標(biāo)簽
git tag 3a
jinjia2 傳入復(fù)雜變量
Flask中Jinja2模板引擎詳解(一)–控制語句和表達(dá)式
@app.route('/hello/<name>')
def hello(name=None):
if name == 'world':
name = '<em>World</em>'
return render_template('hello-1.html', name=name, digits=[1,2,3,4,5],
users=[{'name':'John'},
{'name':'Tom', 'hidden':True},
{'name':'Lisa'},
{'name':'Bob'}])
模板示例:
<dl>
{% for user in users if not user.hidden %}
{% if loop.first %}
<div>User List:</div>
<dd>Deep: {{ loop.depth }}</dd>
{% continue %}
{% endif %}
<div class="{{ loop.cycle('odd', 'even') }}">
<dt>User No {{ loop.index }}:</dt>
<dd>{{ user.name }}</dd>
</div>
{% if loop.last %}
<div>Total Users: {{ loop.length }}</div>
{% endif %}
{% else %}
<li>No users found</li>
{% endfor %}
</dl>
常用過濾器
過濾器名 | 說明 |
---|---|
safe | 渲染時(shí)不轉(zhuǎn)義 |
capitalize | 首字母大寫 |
lower | 轉(zhuǎn)換小寫 |
upper | 轉(zhuǎn)換大寫 |
title | 每個(gè)單詞的首字母大寫 |
trim | 刪除首尾空格 |
striptags | 刪除所有的HTML標(biāo)簽 |
模板語法 {{ name|capitalize }}
git commit -m "jinja2 filter"
,git tag 3b
模板中的 block 和繼承機(jī)制
base.html 文件
<html>
<head>
{% block head %}
<title>{% block title %} {% endblock %}</title>
{% endblock %}
<style>
h1{
background: black;
color: white;
text-align: center;
font-size: 200% ;
padding: 20px;
margin: 5px
}
</style>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
user.html 文件
{% extends "base.html" %}
<!-- title 嵌套在內(nèi)層,先對title模塊進(jìn)行衍生 -->
{% block title %} Index {% endblock %}
<!-- super() 調(diào)用父文件的定義 -->
{% block head %}
{{ super() }}
{% endblock %}
{% block body %}
<h1> Hello {{ name|capitalize }} ! </h1>
{% endblock %}
git add.
,git commit -m "Jinja2 block and inhert"
git tag 3c
使用 Flask-Bootstrap 集成 Twitter Bootstrap
Bootstrap 是一個(gè)用于快速開發(fā) Web 應(yīng)用程序和網(wǎng)站的前端框架宅倒。Bootstrap 是基于 HTML攘宙、CSS、JAVASCRIPT 的拐迁。
安裝flask-bootstrap
pip install flask-bootstrap
初始化 Flask-Bootstrap之后蹭劈,就可以在程序中使用一個(gè)包含所有Bootstrap文件的基模板,這個(gè)模板采用Jinja2的模板繼承機(jī)制线召,讓程序擴(kuò)展一個(gè)具有基本頁面結(jié)構(gòu)的基模板
Bootstrap入門教程
from flask.ext.bootstrap import Bootstrap
# ...
bootstrap = Bootstrap( app )
采用Bootstrap的 user.html
初試flask-bootstrap
{% extends "bootstrap/base.html" %}
<!-- 頁面標(biāo)題 -->
{% block title %} Flasky {% endblock %}
{% block navbar %}
<!-- 導(dǎo)航欄 -->
<!-- navbar-inverse 顏色反色即黑色 -->
<nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<!-- 首個(gè)導(dǎo)航標(biāo)簽字體稍大 -->
<div class="navbar-header">
<a class="navbar-brand" href="/">Flasky</a>
</div>
<!-- 其余導(dǎo)航標(biāo)簽 -->
<div>
<ul class="nav navbar-nav">
<li class="active"><a href="/user/zhanghl">zhanghl</a></li>
<li class="active"><a href="/user/zhanglm">zhanglm</a></li>
</ul>
</div>
</div>
</nav>
{% endblock %}
<!-- 正文 -->
{% block content %}
<div class="container">
<div class="page-header">
<h1> Hello, {{name}}</h1>
</div>
</div>
{% endblock %}
git add.
,git commit -m "Jinja2 bootstrap first demo"
git tag 3d
FLask-Boostarp基模板定義的塊
block名 | 說明 |
---|---|
doc | 整個(gè) html 文檔 |
html_attribs |
<html> 標(biāo)簽屬性 |
html |
<html> 標(biāo)簽中的內(nèi)容 |
head |
<head> 標(biāo)簽中的內(nèi)容 |
title |
<title> 標(biāo)簽中的內(nèi)容 |
metas | 一組 <meta> 標(biāo)簽 |
styles | 層疊樣式表定義 |
body_attribs |
<body> 標(biāo)簽的屬性 |
body |
<body> 標(biāo)簽的內(nèi)容 |
navbar | 用戶定義的導(dǎo)航條 |
<content> |
用戶定義的頁面內(nèi)用 |
scripts | 文檔底部的 JavaScripts 聲明 |
示例:
<!-- scripts 塊示例 -->
{% block scripts %}
{{ super() }}
<script type="text/javascript" src="my-script.js"></script>>
{% endblock %}
<!-- styles 塊示例 -->
{% block styles %}
{{ super() }}
<style type="text/css" src="my-style.css"> </style>
{% endblock %}
git add .
,git commit -m "usual blocks in flask-bootstrap"
自定義錯(cuò)誤處理模塊
# 處理錯(cuò)誤碼的路由
#處理 404 錯(cuò)誤
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
自定義錯(cuò)誤頁面:
{% extends "base.html" %}
{% block title %} Flasky - page not found {% endblock %}
{% block page_content %}
<div class="page-header">
<h1> Not Found !</h1>
</div>
{% endblock %}
git add .
,git commit -m "user define error page "
git tag 3e
創(chuàng)建url的輔助函數(shù)
url_for('視圖函數(shù)名', 動(dòng)態(tài)路由的關(guān)鍵字參數(shù), 額外參數(shù)铺韧,_external=True)
,url_for('user', name='John', page2, _external=True ) 返回 http://localhost:5000/user/John?page=2
靜態(tài)文件
- 大多數(shù) web 程序中還會(huì)使用靜態(tài)文件缓淹,如 圖片哈打,JavaScript 源碼文件 和 CSS
- 靜態(tài)文件對應(yīng)
url_map
中的/static/<filename>
, 存放在 static 文件夾下
在 base.html
中加入 :
{% block head%}
{{ super() }}
<!-- 對于大多數(shù)瀏覽器塔逃,包括 chrome firefox -->
<link rel="icon" href="{{ url_for('static', filename='favicon.ico' )}}" type="image/x-icon">
<!-- 對于 I E -->
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico' )}}" type="image/x-icon">
{% endblock %}
創(chuàng)建 static
文件夾加入 favicon.ico
文件
git add .
,git commit -m "use static file create icon "
git tag 3f
使用 Flask-Moment 本地化日期和時(shí)間
安裝 pip install flask-moment
from flask.ext.moment import Moment
...
moment = Moment( app)
# 把 current_time 傳入模板進(jìn)行渲染
from datatime import datatime
@app.route('/')
def index():
return render_template('index.html', current_time=datatime.utcnow())
<!-- base.html -->
{% block scripts %}
{{ super() }}
<!-- 引入 moment.js 庫 -->
{{ moment.include_moment() }}
{% endblock %}
<!-- 為了處理時(shí)間戳,F(xiàn)lask-Moment 向模板開放了 moment 類 料仗?湾盗??立轧?格粪? -->
<!-- index.html -->
<p>the local data and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}.</p>
git add .
,git commit -m "use flask moment "
git tag 3g