模板: (网页,即template下的html文件)
使用模板的优点:
模板的语法:
1、在模板中获取view中传递的变量值:{{ 变量名key }}
render_template(‘模板文件名’,keyvalue,keyvalue,…)
@app.route('/register')
def register():
# 默认从templates文件夹里查询
r = render_template('register2.html')
print(r)
return r
| 接收类型 | 处理 |
|---|---|
| 接收列表值 | {{ list.0 }} 或 {{ list[0] }} |
| 接收字典值 | {{ dict.key }} 或 {{ dict.get(key) }} |
| 接收对象值 | {{ girl.name }} |
| 应用外部文件名 | url_for(‘static’,filename = ‘css/style.css’) |
| 申明变量进行使用1 | {% set username = ‘zhangsan’ %} {{ username }} |
| 申明变量进行使用2 | {% with num=1— %} {{ num }} {% endwith %} |
example:
app1.py
from flask import Flask,request,render_template
import settings
app = Flask(__name__)
app.config.from_object(settings)
class Girl:
def __init__(self,name,addr):
self.name = name
self.gender = '女'
self.addr = addr
@app.route('/show')
def show():
name = 'haha'
age = 18
friends = ['haha', 'hehe', 'xixi', 'qiaqia']
dicts = {'gift1':'项链','gift2':'鲜花','gift3':'戒指'}
# 创建对象
girlfriend = Girl('翠花','江西')
return render_template('show.html',name=name,age=age,friends=friends,dicts=dicts,girl=girlfriend)
if __name__ == '__main__':
app.run()
show.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div>用户信息展示div>
<p>
用户名是:{{name}} ---- {{age}} --- {{gender}}
<br>
{{friends[0]}}
{{friends.1}}
{{friends[2]}}
{{friends[3]}}
<br>
{{dicts.gift1}}
{{dicts.get('gift2'}}
<br>
{{girl.name}} --- {{girl.gender}} --- {{girl.age}}
p>
<table>
{#动态创建#}
<tr>
<td>td>
tr>
table>
<script>
script>
body>
html>
结果:

| 控制块 | 语法 |
|---|---|
| if判断 | {% if 条件 %} 条件为True后执行的语句 {% else %} 条件为False后执行的语句 {% endif %} |
| for循环 | {% for 变量 in 可迭代对象 %} for要执行的语句 {% endfor %} |
| loop变量循环 | loop.index 序号从1开始 loop.index0 序号从0开始 loop.revindex 序号倒转 loop.revindex0 loop.first 是否第一个 布尔类型 loop.last 是否最后一个 布尔类型 |
example:
app2.py
from flask import Flask,request,render_template
import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/show')
def show1():
girls = ['孙艺珍','松韵','赵丽颖','杨紫','胡冰卿','孙雯']
users = [
{'username': 'haha1', 'password': '123', 'addr': '浙江', 'phone': '10000000000'},
{'username': 'haha2', 'password': '124', 'addr': '浙江', 'phone': '10000000001'},
{'username': 'haha3', 'password': '125', 'addr': '上海', 'phone': '10000000002'},
{'username': 'haha4', 'password': '126', 'addr': '北京', 'phone': '10000000003'},
{'username': 'haha5', 'password': '127', 'addr': '江苏', 'phone': '10000000004'},
{'username': 'haha6', 'password': '128', 'addr': '江西', 'phone': '10000000005'},
]
return render_template('show_controlblock.html',girls=girls,users=users)
if __name__ == '__main__':
app.run()
show_controlblock.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>演示控制块title>
<style>
.a {
color: red;
font-weight: bold;
}
style>
head>
<body>
{# ul...li #}
{# ol...li #}
{# {{girls}} #}
<ul>
{% for girl in girls %}
<li> {{ girl }} li>
{% endfor %}
ul>
<hr>
<ul>
{% for girl in girls %}
{% if girl|length >= 3 %}
<li class="a"> {{ girl }} li>
{% else %}
<li> {{ girl }} li>
{% endif %}
{% endfor %}
ul>
<hr>
<table border="1" cellpadding="0" cellspacing="0" width="50%">
{% for user in users %}
<tr>
<td>{{ user.username }}td>
<td>{{ user.password }}td>
<td>{{ user.addr }}td>
<td>{{ user.phone }}td>
tr>
{% endfor %}
table>
<hr>
<table border="1" cellpadding="0" cellspacing="0" width="50%">
{% for user in users %}
<tr {% if loop.last %} style="background-color: deeppink" {% endif %}>
<td>{{ loop.index0 }}td>
<td>{{ loop.index }}td>
<td>{{ user.username }}td>
<td>{{ user.password }}td>
<td>{{ user.addr }}td>
<td>{{ user.phone }}td>
tr>
{% endfor %}
table>
body>
html>
结果:

过滤器的本质就是函数
模板语法中过滤器:
{{ 变量名 | 过滤器 }}
{{ 变量名 | 过滤器(*args) }}
常见的过滤器:
1、safe : 转义 保留样式,不使标签进行转义,让其依然可展示样式
2、capitalize : 单词首字母大写
3、lower/upper:单词大小写转换
4、title : 一句话中的每个单词的首字母大写
5、reverse : 单词字母倒拼
6、format : 格式转换
7、truncate : 返回一个截断的长度字串
8、列表中存在的过滤器:
{{ girls | first }}
{{ girls | last }}
{{ girl | length }}
{{ [1,3,5,7,9] | sum }}
{{ [2,0,1,5.8,3] | sort }}
9、tojson() : 将给定的对象转换为JSON表示
10、字典中存在的过滤器:
获取值:
{% for v in users.0.values() %}
{{ v }}
{% endfor %}
获取键:
{% for v in users.0.keys() %}
{{ v }}
{% endfor %}
获取键值对:
{% for k,v in users.0.items() %}
{{ k }}---{{ v }}
{% endfor %}
11、自定义过滤器
1、通过flask模块中的add_template_filter方法
def replace_hello(value):
print('---->',value)
value = value.replace('hello','')
print('=======>',value)
return value.strip()
app.add_template_filter(replace_hello,'replace')
2、使用装饰器完成
@app.template_filter('listreverse')
def reverse_list(li):
temp_li = list(li)
temp_li.reverse()
return temp_li
3、手动添加到应用jinja_env
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
example:
app3.py
from flask import Flask,request,render_template
import settings
# 包含过滤器、判断条件if、循环条件for
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/show')
def show1():
girls = ['孙艺珍','松韵','赵丽颖','杨紫','胡冰卿','孙雯']
users = [
{'username': 'haha1', 'password': '123', 'addr': '浙江', 'phone': '10000000000'},
{'username': 'haha2', 'password': '124', 'addr': '浙江', 'phone': '10000000001'},
{'username': 'haha3', 'password': '125', 'addr': '上海', 'phone': '10000000002'},
{'username': 'haha4', 'password': '126', 'addr': '北京', 'phone': '10000000003'},
{'username': 'haha5', 'password': '127', 'addr': '江苏', 'phone': '10000000004'},
{'username': 'haha6', 'password': '128', 'addr': '江西', 'phone': '10000000005'},
]
girls.append('zhangsan')
msg = '520快乐!
'
n1 = 'hello'
return render_template('show_controlblock.html',girls=girls,users=users,msg=msg,n1=n1)
@app.route('/')
def hello_word():
msg = 'hello everyone hello world'
li = [3,4,5]
return render_template('define_filter.html',msg=msg,li=li)
# 第一种方式
# 过滤器本质就是函数
def replace_hello(value):
print('---->',value)
value = value.replace('hello','')
print('=======>',value)
return value.strip()
app.add_template_filter(replace_hello,'replace')
# 第二种方式 装饰器
@app.template_filter('listreverse')
def reverse_list(li):
temp_li = list(li)
temp_li.reverse()
return temp_li
if __name__ == '__main__':
app.run()
show_controlblock.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>演示控制块title>
<style>
.a {
color: red;
font-weight: bold;
}
style>
head>
<body>
{# ul...li #}
{# ol...li #}
{# {{girls}} #}
<ul>
{% for girl in girls %}
<li> {{ girl }} li>
{% endfor %}
ul>
<hr>
<ul>
{% for girl in girls %}
{% if girl|length >= 3 %}
<li class="a"> {{ girl }} li>
{% else %}
<li> {{ girl }} li>
{% endif %}
{% endfor %}
ul>
<hr>
<table border="1" cellpadding="0" cellspacing="0" width="50%">
{% for user in users %}
<tr>
<td>{{ user.username }}td>
<td>{{ user.password }}td>
<td>{{ user.addr }}td>
<td>{{ user.phone }}td>
tr>
{% endfor %}
table>
<hr>
<table border="1" cellpadding="0" cellspacing="0" width="50%">
{% for user in users %}
<tr {% if loop.last %} style="background-color: deeppink" {% endif %}>
<td>{{ loop.index0 }}td>
<td>{{ loop.index }}td>
<td>{{ user.username }}td>
<td>{{ user.password }}td>
<td>{{ user.addr }}td>
<td>{{ user.phone }}td>
tr>
{% endfor %}
table>
body>
html>
define_filter.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过滤器的使用title>
head>
<body>
当前用户共:{{ girls | length }} 人
<br>
{# 过滤器转义 #}
{{ len(girls) }}
<br>
{{ msg | safe }}
<br>
{{ n1 | capitalize }}
<br>
{{ n1 | upper }}
<br>
{{ n2 | lower }}
<br>
{{ n1 | reverse }}
<br>
{{ '%s id %d' | format('lili',18 }}
<br>
{{ 'hello world' | truncate(7) }}
{# 列表过滤器的使用 #}
{{ girls | first }}
<br>
{{ girls | last }}
<br>
{{ girl | length }}
<br>
{{ [1,3,5,7,9] | sum }}
<br>
{{ [2,0,1,5.8,3] | sort }}
<br>
<p>
{{ users.0 }}
<br>
{% for v in users.0.values() %}
<p>{{ v }} p>
{% endfor %}
<hr>
{% for k,v in users.0.items() %}
<p>{{ k }}---{{ v }}p>
{% endfor %}
p>
body>
html>
结果:


模板继承:
需要模板继承的情况:
1、多个模板具有完全相同的顶部和底部
2、多个模板具有相同的模板内容,但是内容中部分不一样
3、多个模板具有完全相同的模板
标签:
{% block name %}
{% endblock %}
1、先在父模板中使用标签留出变化区(注意:样式和脚本需要提前预留)
{% block name %}
{% endblock %}
2、子模板继承父模板
{% extends '父模板名称' %}
3、再在子模板中通过父模板中响应名称的变量名,进行填充
{% block name %}
变化内容
{% endblock %}
子模板引入父模板
| include:包含 | 使用场景:在A,B,C页面都有共同的部分,但是其他页面没有这部分 步骤: 1、先定义一个公共的模板部分:.html 2、使用include导入进需要使用的文件(注意:文件夹必须是在template里面) {% include ‘文件夹/.html’ %} |
| 宏:macro | 1、把它看作是jinja2的一个函数,这个函数可以返回一个HTML字符串 2、目的:代码可以复用,避免代码冗余 定义的两种方式: 1、在模板中直接定义: 类似:macro1.html 中定义方式 2、将所有宏提取到一个模板中:macro.html 使用时进行导入: {% import ‘macro.html’ as 调用名 %} {{ 调用名.宏(参数值) }} |
| {{ url_for(‘static’,filename=‘’) }}:加载static下面的静态文件 | 使用场景:加载例如javaScript或css等文件 |
example:
app4.py
from flask import Flask,request,render_template
import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/base')
def load_inherit():
return render_template('inherit.html')
@app.route('/')
def index():
return render_template('inherit2.html')
@app.route('/welcome')
def welcome():
return render_template('include.html')
@app.route('/macro')
def use_macro():
return render_template('macro/macro1.html')
@app.route('/macro1')
def use_macro1():
return render_template("macro/macro2.html")
@app.route('/index')
def welcome():
return render_template('index.html')
if __name__ == '__main__':
app.run()
inherit.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
{% block title %}父模板的title{% endblock %}
title>
<style>
#head{
height : 50px;
background-color : bisque;
}
#head ul{
list-style: none;
}
#head ul li{
float : left;
width : 100px;
text-align : center;
font-size : 50px;
line-height: 50px;
}
#middle{
height : 900px;
background-color : azure;
}
#foot{
height : 50px;
line-height : 50px;
background-color : darkseagreen;
}
style>
{% block mycss %}
{% endblock %}
head>
<body>
<div id="head">
<ul>
<li>首页li>
<li>秒杀li>
<li>超市li>
<li>图书li>
<li>会员li>
ul>
div>
<div id="middle" >
{% block middle %}
<button>我是中间部分button>
{% endblock %}
div>
<div id="foot">
我是底部部分
div>
{% block myjs %}
{% endblock %}
body>
html>
inherit2.html
{% extends 'base.html' %}
{% block title %}
首页
{% endblock %}
{% block mycss %}
<style>
#middle{
background-color : deeppink;
}
.div1{
width: 33%;
height: 500px;
float: left;
border: 1px solid red;
}
style>
<# link rel="stylesheet" href="../static/css/style.css" #>
<link rel="stylesheet" href="{{ url_for('static',filename = 'css/style.css') }}">
{% endblock %}
{% block myjs %}
<script>
btn = document.getElementById('btn')
btn.onclick(function(){
alert('别点我啊!')
})
script>
{% endblock %}
{% block middle %}
<div class="div1" id="d1">div>
<div class="div1">div>
<div class="div1">div>
<img src="{{ url_for('static',filename='images/a.png')}}" alt="" >
{% endblock %}
header.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>头部title>
head>
<body>
<div style="heigh: 50px;background-color: deeppink">div>
body>
html>
include.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎页面title>
head>
<body>
{% include 'common/header.html' %}
<div style="background-color: darkseagreen; width: 100px; ">div>
body>
html>
macro/macro1.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>宏title>
head>
<body>
{# 定义宏 #}
{% macro form(action,value='登录',method='post') %}
<form action="{{ action }}" method="{{ method }}">
<input type="text" value="" placeholder="用户名" name="username">
<br>
<input type="password" placeholder="密码" name="password">
<br>
<input type="submit" value="{{ value }}">
form>
{% endmacro %}
{# 调用宏 #}
{{ form('/') }}
body>
html>
macro/macro.html
{# 定义宏 #}
{% macro form(action,value='登录',method='post') %}
<form action="{{ action }}" method="{{ method }}">
<input type="text" value="" placeholder="用户名" name="username">
<br>
<input type="password" placeholder="密码" name="password">
<br>
<input type="submit" value="{{ value }}">
form>
{% endmacro %}
macro/macro2.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>宏的使用2title>
head>
<body>
{% import 'macro/macro.html' as f %}
{{ f.form('welcome',value='注册') }}
{# 申明变量进行使用 #}}
{% set username = 'zhangsan' %}
{{ username }}
{% with num=1--- %}
{{ num }}
{% endwith %}
body>
html>
hello.js
function sayHello() {
alert("Hello World")
}
index.html
<html>
<head>
<script type = "text/javascript"
src = "{{ url_for('static', filename = 'hello.js') }}" >script>
head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
body>
html>
| 类型 | 方法 |
|---|---|
| 变量 | {{ name }} |
| 块 | {% if 条件 %} …{% endif %} {% for 条件 %} …{% endfor %} {% block 条件 %} …{% endblock %} {% macro 条件 %} …{% endmacro % |
| {% include ‘’ %} 包含 {% import ‘’ %} 导入 {% extends ‘’ %} 继承 | |
| {{ url_for(‘static’,filename=‘’) }} {{ 宏name(***) }} |