flask框架jinja2模板与模板继承实例分析

yipeiwu_com5年前Python基础

本文实例讲述了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"%}标签是这里的关键,告诉模板引擎这个模板继承自另外一个模板。该标签必须是子模板的第一个标签,解释器会自动将父亲的内容复制到子模板中!

结果应该是这样:

<!DOCTYPE html>
<html>
<head>
  <title>模板继承</title>
</head>
<body>
  <span>这是基模板</span>
  <div id="content">
      <p class="importtant">我在子模板</p>
    </div>
</body>
</html>

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

Python基于DES算法加密解密实例

本文实例讲述了Python基于DES算法加密解密实现方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 from functools import par...

python同义词替换的实现(jieba分词)

python同义词替换的实现(jieba分词)

TihuanWords.txt文档格式注意:同一行的词用单个空格隔开,每行第一个词为同行词的替换词。年休假 年假 年休究竟 到底回家场景 我回来了代码import jieba...

使用Python进行体育竞技分析(预测球队成绩)

使用Python进行体育竞技分析(预测球队成绩)

今天我们用python进行体育竞技分析,预测球队成绩 一. 体育竞技分析的IPO模式 : 输入I(input):两个球员的能力值,模拟比赛的次数(其中,运动员的能力值,可以通过发球方赢得...

python每天定时运行某程序代码

思路:利用time函数返回的时间字符串与指定时间字符串做比较,相等的时候执行对应的操作。不知道大家的思路是什么,感觉这样比较耗CPU。。。。 此处设置为15:30:10 输出相应内容,需...

Python内建模块struct实例详解

本文研究的主要是Python内建模块struct的相关内容,具体如下。 Python中变量的类型只有列表、元祖、字典、集合等高级抽象类型,并没有像c中定义了位、字节、整型等底层初级类型。...