本文實例講述了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 %} #表達式
<li href='{{ item }}'>{{ item }}</li> #輸出變量
{% endfor %}
</ul>
<h2>HelloWorld</h2>
{{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"%}標簽是這里的關鍵,告訴模板引擎這個模板繼承自另外一個模板。該標簽必須是子模板的第一個標簽,解釋器會自動將父親的內容復制到子模板中!
結果應該是這樣:
<!DOCTYPE html>
<html>
<head>
<title>模板繼承</title>
</head>
<body>
<span>這是基模板</span>
<div id="content">
<p class="importtant">我在子模板</p>
</div>
</body>
</html>
希望本文所述對大家基于flask框架的Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。