flask之jinji2模板介绍
1.1.模板傳參
(1)主程序
from flask import Flask,render_templateapp = Flask(__name__)@app.route('/') def hello_world():context = {'username':'derek','age':18,'gf':{'name':'xxx','height':160}}return render_template('index.html',**context) #加雙下劃綫,就可以直接獲取key和value了if __name__ == '__main__':app.run(debug=True)(2)index.html
<h2>模板中渲染數據</h2><p>{{ username }}</p><p>{{ age }}</p><p>{{ gf.name }}</p><p>{{ gf['height'] }}</p>?
1.2.過濾器
?常用的過濾器
- abs:絕對值
- default:如果當前變量沒有值,則會使用參數中的值來替代
- escape:轉義字符
- first:返回一個序列的第一個元素
- format:格式化字符串
- last:返回一個序列的最后一個元素
- length:返回一個序列的長度
- join:拼接字符串
- safe:關掉轉義
- int:轉為int類型
- float:轉為浮點類型
- lower:轉換為小寫
- upper:轉換為答謝
- replace:替換
- truncate:截取length長度的字符串
- striptags:刪除字符串中所有的html標簽,如果出現多個空格,將替換成一個空格
?default過濾器的使用
主程序
from flask import Flask,render_template app = Flask(__name__)@app.route('/') def hello_world():context = {'position':-9,'signature':None #個性簽名 }return render_template('index.html',**context)if __name__ == '__main__':app.run(debug=True)index.html
<h2>過濾器</h2><p>{{ position|abs }}</p><p>個性簽名:{{ signature|default('此人很懶,沒有留下任何說明',boolean=True) }}</p>也可以用or的方式
<h2>過濾器</h2><p>{{ position|abs }}</p> {# <p>個性簽名:{{ signature|default('此人很懶,沒有留下任何說明',boolean=True) }}</p>#}<p>個性簽名:{{ signature or '此人很懶,沒有留下任何說明' }}</p>1.3.自定義過濾器
????? 過濾器本質上就是一個函數,如果在模板中調用這個過濾器,那么就會將這個變量的值作為第一個參數傳給過濾器這個函數,
然后函數的返回值會作為這個過濾器的返回值。需要使用一個裝飾器:@app.template_filter('args')
?
實例:自定義時間處理過濾器
?主程序
from flask import Flask,render_template from datetime import datetime app = Flask(__name__)@app.route('/') def hello_world():context = {'create_time':datetime(2018,5,25,17,52,10)}return render_template('index.html',**context)@app.template_filter('handle_time') #括號里面是自己給過濾器起的名字 def handle_time(time):'''1.如果時間間隔小與1分鐘以內,就顯示“剛剛”2.如果是1小時以內,顯示“xx分鐘”3.如果24h以內,顯示“xx小時前”4.如果大于24小時小與30天,顯示“xx天前”5.大于一個月,顯示具體的時間:param time::return:'''if isinstance(time,datetime):now = datetime.now()timestamp = (now-time).total_seconds() #當前時間離創建時間的秒數if timestamp < 60: #60s以內return "剛剛"elif timestamp >= 60 and timestamp < 60*60:minutes = timestamp / 60return "%s分鐘前"%int(minutes)elif timestamp >= 60*60 and timestamp < 60*60*24:hours = timestamp / (60*60)return '%s小時前'%int(hours)elif timestamp >= 60*60*24 and timestamp < 60*60*24*30:days = timestamp / (60*60*24)return '%s天前'%int(days)else:return time.strftime('%Y/%m/%d %H:%M')else:return timeif __name__ == '__main__':app.run(debug=True)index.html
<h2>自定義時間過濾器</h2>{{ create_time|handle_time }}1.4.if和for的使用
for中包含以下變量,可以用來獲取當前的遍歷狀態
- loop.index
- loop.index0
- loop.first
- loop.last
- loop.length
?
if和for簡單用法
from flask import Flask,render_templateapp = Flask(__name__) app.config.update({'DEBUG':True,'TEMPLATES_AUTO_RELOAD':True })@app.route('/') def hello_world():context = {'age':20,'users':['tom','jack','alice'],'person':{'name':'derek','age':18}}return render_template('index.html',**context)if __name__ == '__main__':app.run(debug=True)index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body>{% if age >= 18 %}歡迎{% else %}無權限{% endif %}<ul>{% for user in users %}<li>{{ user }}</li>{% endfor %}</ul><table><thead><tr><th>用戶名</th><th>年齡</th></tr></thead><tbody><tr>{% for key,value in person.items() %}<td>{{ value }}</td>{% endfor %}</tr></tbody></table></body> </html>1.5.宏的使用和導入
模板的宏跟python中的函數類似,可以傳遞參數,但是不能有返回值,可以將一些經常用到的代碼片段放到宏中,然后把一些
不固定的值抽取出來當成一個變量。
(1)簡單使用實例
{# 定義一個宏,input是宏的名字,里面三個參數,可以指定默認參數值,也可以調用的傳參#}{% macro input(name="",value="",type="text") %}<input name="{{ name }}" value="{{ value }}" type="{{ type }}">{% endmacro %}<form><p>用戶名:{{ input('username') }}</p><p>密碼:{{ input('password',type="password" )}}</p><p> {{ input(value="提交",type="submit" )}}</p></form>(2)宏的兩種導入方式
新建macros.html
{% macro input(name="",value="",type="text") %}<input name="{{ name }}" value="{{ value }}" type="{{ type }}">{% endmacro %}index.html中導入使用宏
{#第一種#} {# with context可以把后端傳到當前模板的變量傳到定義的宏里面#} {% import "macros.html" as macro with context %} {#第二種#} {% from "macros.html" import input as input_field %}<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> {# 第一種#}<form><p>用戶名:{{ macro.input('username') }}</p><p>密碼:{{ macro.input('password',type="password" )}}</p><p> {{ macro.input(value="提交",type="submit" )}}</p></form>{# 第二種#}<form><p>用戶名:{{ input_field('username') }}</p><p>密碼:{{ input_field('password',type="password" )}}</p><p> {{ input_field(value="提交",type="submit" )}}</p></form></body> </html>1.6.set、with在模板中自定義變量
?(1)set
在模板中可以使用set來定義變量,一旦定義了這個變量,在后面的代碼中都可以使用,index.html
{% set usernmae='derek' %}<p>用戶名:{{ usernmae }}</p>(2)with
with語句定義的變量,只能在with語句代碼塊(endwith)里面使用,超過代碼塊,就不能再使用了,set語句沒有end,全局使用
{% with age=18 %}<p>年齡:{{ age }}</p>{% endwith %}?
1.7.藍圖的使用
目錄如下:
(1)news.py
from flask import Blueprintnews_bp = Blueprint('new',__name__,url_prefix='/news') @news_bp.route('/list/') def news_list(): return '新聞列表'(2)user.py
from flask import Blueprint# 1.定義一個藍圖,'user':藍圖的名字,url_prefix='/user':給url加一個前綴,注意后面不要加'/' user_bp = Blueprint('user',__name__,url_prefix='/user') @user_bp.route('/profile/') def profile(): return '個人中心'(3)bluepoint_demo.py
from flask import Flask,url_for # 2.導入 from blueprints.user import user_bp from blueprints.news import news_bp app = Flask(__name__) # 3.注冊藍圖 app.register_blueprint(user_bp) app.register_blueprint(news_bp) @app.route('/') def hello_world(): return 'Hello World!' with app.test_request_context(): print(url_for('new.news_list')) # /news/list/ 通過url_for反轉url的時候要加藍圖的名字 print(url_for('user.profile')) # /user/profile/ if __name__ == '__main__': app.run(debug=True)?
?
轉載于:https://www.cnblogs.com/caodneg7/p/10093780.html
總結
以上是生活随笔為你收集整理的flask之jinji2模板介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 例子简单说说C# ref和out
- 下一篇: 优化小技巧——复杂属性对象的read模式