flask框架jinja2模板與模板繼承實例分析
本文實例講述了flask框架jinja2模板與模板繼承。分享給大家供大家參考,具體如下:
jinja2模板
from werkzeug.contrib.cache import SimpleCache from flask import Flask, request, render_template,redirect,abort, url_for CACHE_TIME = 300 cache = SimpleCache() cache.timeout = CACHE_TIME app = Flask(__name__) @app.before_request def return_cached(): if not request.values: response = cache.get(request.path) if response: print("Got the page from cache!") return response print("Will load the page!") @app.after_request def cache_response(response): print("aaaaaaaaaaaaaaaaaaaaaa") if not request.values: cache.set(request.path, response, CACHE_TIME) return response @app.teardown_request def teardown_request(response): print('llllllllllllllllllllllll') return "llllllllllllllllllllll" # @app.route('/') @app.route('/get_index') def index(): return render_template('jinja2.html', a_variable="Developer", navigation=["http://www.163.com", "www.baidu.com"]) if __name__ == '__main__': app.run(port=8000)
jinja2.html必須在templates文件夾下,例子如下:
<!DOCTYPE html> <html> <head> <title>jinja2_test</title> </head> <body> <ul id="navigation"> {% for item in navigation %} #表達(dá)式 <li href='{{ item }}'>{{ item }}</li> #輸出變量 {% endfor %} </ul> <h1>HelloWorld</h1> {{a_variable}}#輸出變量 {# aaaa #}#模板注釋,加載自動刪除 </body> </html>
jinja2模板繼承
父親:
<!DOCTYPE html> <html> <head> <title>模板繼承</title> </head> <body> <span>這是基模板</span> <div id="content">{% block content %}{% endblock %}</div> </body> </html>
用{% block content %}{% endblock %}
包含jinja2的字模板塊;
子:
<!DOCTYPE html> <html> <head> <title>模板繼承</title> </head> <body> {% extend "jinja2_模板繼承.html"%} {% block content %} <p class="importtant">我在子模板</p> </body> </html>
{% extends "jinja2_模板繼承.html"%}
標(biāo)簽是這里的關(guān)鍵,告訴模板引擎這個模板繼承自另外一個模板。該標(biāo)簽必須是子模板的第一個標(biāo)簽,解釋器會自動將父親的內(nèi)容復(fù)制到子模板中!
結(jié)果應(yīng)該是這樣:
<!DOCTYPE html> <html> <head> <title>模板繼承</title> </head> <body> <span>這是基模板</span> <div id="content"> <p class="importtant">我在子模板</p> </div> </body> </html>
希望本文所述對大家基于flask框架的Python程序設(shè)計有所幫助。
相關(guān)文章
基于Python實現(xiàn)GeoServer矢量文件批量發(fā)布
由于矢量圖層文件較多,手動發(fā)布費時費力,python支持的關(guān)于geoserver包又由于年久失修,無法在較新的geoserver版本中正常使用。本文為大家準(zhǔn)備了Python自動化發(fā)布矢量文件的代碼,需要的可以參考一下2022-07-07Python利用subplots_adjust方法解決圖表與畫布的間距問題
這篇文章主要介紹了如何在使用python?的?matplotlib庫繪圖時,?使用subplots_adjust()方法來調(diào)整圖表與畫布之間的間距,以及圖表與圖表之間的間距,感興趣的可以了解一下2022-04-04