flask框架jinja2模板與模板繼承實(shí)例分析
本文實(shí)例講述了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 #}#模板注釋,加載自動(dòng)刪除
</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)鍵,告訴模板引擎這個(gè)模板繼承自另外一個(gè)模板。該標(biāo)簽必須是子模板的第一個(gè)標(biāo)簽,解釋器會(huì)自動(dòng)將父親的內(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è)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)IP代理批量采集的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)IP代理批量采集,并檢測代理是否可用。文中的示例代碼講解詳細(xì),需要的可以參考一下2022-09-09
基于Python實(shí)現(xiàn)GeoServer矢量文件批量發(fā)布
由于矢量圖層文件較多,手動(dòng)發(fā)布費(fèi)時(shí)費(fèi)力,python支持的關(guān)于geoserver包又由于年久失修,無法在較新的geoserver版本中正常使用。本文為大家準(zhǔn)備了Python自動(dòng)化發(fā)布矢量文件的代碼,需要的可以參考一下2022-07-07
django實(shí)現(xiàn)支付寶支付實(shí)例講解
在本篇文章里小編給大家整理的是一篇關(guān)于django支付寶支付的代碼實(shí)例內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2019-10-10
Python利用subplots_adjust方法解決圖表與畫布的間距問題
這篇文章主要介紹了如何在使用python?的?matplotlib庫繪圖時(shí),?使用subplots_adjust()方法來調(diào)整圖表與畫布之間的間距,以及圖表與圖表之間的間距,感興趣的可以了解一下2022-04-04

