Jinja2是基于python的模板引擎,功能比较类似于于PHP的smarty,J2ee的Freemarker和velocity。 它能完全支持unicode,并具有集成的沙箱执行环境,应用广泛。jinja2使用BSD授权。
例:
{% block title %}{% endblock %}
{% for user in users %}
- {{ user.username }}
{% endfor %}
特性:
from flask import Flask, render_template
app = Flask(__name__)
class User(object):
def __init__(self, name, passwd):
self.name = name
self.passwd = passwd
def __str__(self):
return '' %(self.name)
# 视图函数
@app.route('/')
def index():
"""下面的变量均为我们要传递的参数"""
name = 'westos'
li = [1,2,3,4]
d = dict(a=1, b=3, c=6)
u = User('root', 'redhat')
return render_template('index.html', #这里为链接的页面内容
name = name, #传递参数
li = li, #传递参数
d = d, #传递参数
u = u) #传递参数
if __name__ == "__main__":
# 运行web app
app.run(host='0.0.0.0', port=9008)
index.html页面
主页
字符串变量显示
{{ name }}
列表
{{ li }}
字典
{{ d }}
{% for i in d %}
{% if i in ['a', 'c'] %}
{{ i }}
{{ d[i]}}
{% else %}
{{ i }}
{{ d[i]}}
{% endif %}
{% endfor %}
对象
{{ u }}
用户名
密码
{{ u.name }}
{{ u.passwd }}
变量可以通过 过滤器 修改。过滤器与变量用管道符号( | )分割,并且也 可以用圆括号传递可选参数。多个过滤器可以链式调用,前一个过滤器的输出会被作为 后一个过滤器的输入。
例如 {{ name|striptags|title }} 会移除 name 中的所有 HTML 标签并且改写 为标题样式的大小写格式。过滤器接受带圆括号的参数,如同函数调用。这个例子会 把一个列表用逗号连接起来: {{ list|join(', ') }} 。
from flask import Flask,render_template
app = Flask(__name__)
class user(object):
def __init__(self,name,passwd):
self.name = name
self.passwd = passwd
def __str__(self):
return "User : %s" %(self.name)
@app.route('/')
def index():
name = "reDhat"
li = [1,2,4,5]
dic = dict(a=1,b=2,c=3)
u = user('student','redhat')
return render_template('index2.html',name=name,li = li,dic = dic, u = u)
if __name__ == "__main__":
app.run('0.0.0.0',port=9009)
index.html 页面过滤
Title
字符串进行过滤
{{ name }}
{{ name | upper }}
{{ name | lower }}
{{ name | capitalize }}
{{ name | upper |reverse }}
对数字进行过滤操作
{{ 1.534234234 | round }}
{{ 1.534234234 | round(3 , 'floor') }}
{{ 1.534234234 | abs }}
列表过滤
{{ li }}
{{li|first}}
{{li|last}}
{{ li|length}}
{{ li|sum}}
{{ li|sort}}
{{ li|join(',')}}
字典
{% for i in dic %}
{% if i in ['a','b']%}
{{ i }}
{{ dic[i] }}
{% else %}
{{i}}
{{dic[i] }}
{% endif %}
{% endfor %}
用户名
密码
{{ u.name}}
{{ u.passwd}}
import time
from flask import Flask,render_template
import os
app = Flask(__name__)
class user(object):
def __init__(self,name,passwd):
self.name = name
self.passwd = passwd
def __str__(self):
return "User : %s" %(self.name)
@app.route('/')
def index():
name = "reDhat"
li = [1,2,4,5]
dic = dict(a=1,b=2,c=3)
u = user('student','redhat')
socket = ('172.25.254.66',80)
oldtime = os.path.getctime('/etc/passwd')
return render_template('index3.html',name=name,li = li,dic = dic, u = u,socket = socket, oldtime = oldtime)
#让列表倒叙
def sub(l):
return l[::-1]
#重整ip
def format_addr_port(value):
res = value[0] + ':' +str(value[1])
return res
#时间格式化输出,变成我们能看懂的时间
def format_date(timestamp):
timeStruct = time.localtime(timestamp)
res = time.strftime('%Y-%m-%d %H:%M:%S', timeStruct)
return res
app.add_template_filter(sub,'sub')
app.add_template_filter(format_addr_port,'format_socket')
app.add_template_filter(format_date,'format_time')
if __name__ == "__main__":
app.run('0.0.0.0',port=9002)
index3.html前端显示
Title
{{ li | sub()}}
{{ socket | format_socket }}
{{ oldtime | format_time }}
宏类似常规编程语言中的函数。它们用于把常用行为作为可重用的函数,取代 手动重复的工作。 例子:
{% macro input(name, value='', type='text', size=20) -%} {%- endmacro %}
在命名空间中,宏之后可以像函数一样调用:
{{ input('username') }}
{{ input('password', type='password') }}
如果宏在不同的模板中定义,你需要首先使用 import
{% from 'base/macro/submit.macro' import test %}
2、例:
主函数
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index4.html')
if __name__=="__main__":
app.run('0.0.0.0',port=9010)
index4.html
Title
macro.html
{% macro input(name , type='text', value='') %}
{% endmacro%}}
在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。
UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。
时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。
元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:
索引(Index) | 属性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 61 |
6 | tm_wday(weekday) | 0 - 6(0表示周日) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为-1 |
2)time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
3)time.time():返回当前时间的时间戳。
4)time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
5)time.strptime(string[, format]):把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
import time
import os
print(time.time())
print(time.ctime())
t = time.localtime()
print(t.tm_year)
# 1. 想把元组的时间转换为时间戳
print(time.mktime(t))
# 2. 把时间戳转换为元组的
print(time.localtime(os.path.getatime('/etc/group')))
# 3. 把时间戳转化为字符串的时间
time.ctime()
# 4. 元组----> 字符串
print(time.strftime('%Y-%m-%d', t))
# 5. 字符串---> 元组
print(time.strptime('2018-10-10', '%Y-%m-%d'))
一个系统网站往往需要统一的结构,这样看起来比较“整洁”。
比如,一个页面中都有标题、左侧菜单、右侧内容显示、底部等四部分。
如果在每一个网页中都进行这些部分的编写,那么整个网站将会有很多冗余部分,而且,对于网页程序的编写也不美观。
这时候可以采用模板继承,即将相同的部分提取出来,形成一个base.html,具有这些相同部分的网页通过继承base.html来具有对应的模块。
这里采用的Jinja2中的模板继承机制来实现——将页面划分为标题栏、左侧菜单栏和右侧主页面。
模板的继承语法:
1. 如何继承某个模板? {% extends "模板名称" %} 2. 如何挖坑和填坑? 挖坑: {% block 名称 %} 默认值 {% endblock %} 填坑: {% block 名称 %} {% endblock %} 3. 如何调用/继承被替代的模板? 挖坑: {% block 名称 %} 默认值 {% endblock %} 填坑: {% block 名称 %} #如何继承挖坑时的默认值? {{ super() }} # 后面写新加的方法. ........ {% endblock %}总函数
from flask import Flask,render_template
app = Flask(__name__)
# 视图函数
@app.route('/')
def index():
return render_template('index5.html')
# 视图函数
@app.route('/login/')
def login():
return render_template('login.html')
if __name__ == "__main__":
# 运行web app
app.run(host='0.0.0.0', port=9004)
login.html
{% extends "base.html"%}
{% block title%}
登陆页面
{% endblock%}
{% block content%}
{% import 'macro.html' as macro %}
用户名:{{ macro.input(name='name') }}
密码:{{ macro.input(name='passwd' , type='password') }}
{{macro.input(name='' ,type="submit",value ="注册") }}
{% endblock%}
index5.html
{% extends "base.html"%}
{% block title %}
首页
{% endblock%}
{% block content %}
hello
{% endblock%}
总继承的页面:base.html
{% block title%} {% endblock%}| 西部开源技术中心
西部开源技术中心
029-86699937 029-88262419
首页
课程中心
教学体系
新闻咨询
学习资源
Linux企业文化
{% block content%}
{% endblock %}
地址:西安市太白南路181号西高新西部电子社区A座B区二楼
电话:029-86699937 029-88262419
省去了大量重复的代码,节省代码量。