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 %} #表達式
<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"%}標簽是這里的關(guān)鍵,告訴模板引擎這個模板繼承自另外一個模板。該標簽必須是子模板的第一個標簽,解釋器會自動將父親的內(nèi)容復制到子模板中!
結(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自動化辦公之定時發(fā)送郵件的實現(xiàn)
python中的schedule模塊可以使我們方便簡單的使用定時任務(wù),即在特定的時間自動的執(zhí)行一些任務(wù)的功能,本文將用這一模塊實現(xiàn)郵件自動發(fā)送,需要的可以參考一下2022-05-05
Python實現(xiàn)復雜對象轉(zhuǎn)JSON的方法示例
這篇文章主要介紹了Python實現(xiàn)復雜對象轉(zhuǎn)JSON的方法,結(jié)合具體實例形式分析了Python針對json轉(zhuǎn)換的相關(guān)操作技巧,需要的朋友可以參考下2017-06-06
Python實現(xiàn)word2Vec model過程解析
這篇文章主要介紹了Python實現(xiàn)word2Vec model過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
解決pycharm無法識別本地site-packages的問題
今天小編就為大家分享一篇解決pycharm無法識別本地site-packages的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10

