flask结合jinja2使用详解
jinja2简介
特征
- 沙箱中执行
- 强大的 html 自动转义系统保护系统免受 XSS
- 模板继承
- 及时编译最优的 python 代码
- 可选提前编译模板的时间
- 易于调试。异常的行数直接指向模板中的对应行。
- 可配置的语法
Jinja 分隔符
Jinja 在模板字符串中使用各种分隔符。
{% %}
-陈述{{ }}
-要打印到模板输出的表达式{# #}
-模板输出中未包含的注释# ##
-行语句
模板渲染
app.py
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/blog/<int:blog_id>')
def blog(blog_id):
page = request.args.get('page', default=1, type=int)
return render_template('blog.html',id=blog_id,page=page)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>coleak's page</title>
</head>
<body>
<h1>START</h1>
<h2>coleak2</h2>
<h3>coleak3</h3>
<h4>coleak4</h4>
<h5>coleak5</h5>
<h1>END</h1>
</body>
</html>
blog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>这里是第{{ id }}位博客主的第{{ page }}页博客</h1>
</body>
</html>
效果测试
Http://10.133.5.113:8000
http://10.133.5.113:8000/blog/3
http://10.133.5.113:8000/blog/3?page=6
模板访问变量属性
app.py
from flask import Flask,render_template,request
app = Flask(__name__)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/blog/<int:blog_id>')
def blog(blog_id):
page = request.args.get('page', default=1, type=int)
return render_template('blog.html',id=blog_id,page=page)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>coleak's page</title>
</head>
<body>
<h1>START</h1>
<div><h1>welcome {{ user.username }}</h1></div>
<div><h1>你的别名是{{ person.username }},邮箱是{{ person["email"] }}</h1></div>
<h2>coleak2</h2>
<h3>coleak3</h3>
<h4>coleak4</h4>
<h5>coleak5</h5>
<h1>END</h1>
</body>
</html>
效果测试
内置过滤器的使用
可以将过滤器应用于数据以对其进行修改。 例如,sum 筛选器可以对数据求和,escape 筛选器对它们进行转义,sort 筛选器对它们进行排序。
app.py
from flask import Flask,render_template,request
app = Flask(__name__)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/filter')
def filter():
User1=user('coleak',-123.456)
return render_template("filter.html",user=User1)
if __name__ == '__main__':
app.run()
filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过滤器</title>
</head>
<body>
<div>{{ user.username }}长度为{{ user.username|length }}</div>
<div>{{ user.email }}绝对值为{{ user.email|abs }}</div>
</body>
</html>
效果测试
自定义过滤器
app.py
from flask import Flask,render_template,request
from datetime import datetime
app = Flask(__name__)
def my_filter(value,fORMat="%Y年-%m月-%d日 %H时:%M分"):
return value.strftime(format)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
app.add_template_filter(my_filter,"time_filter")
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/filter')
def filter():
mytime=datetime.now()
User1=user('coleak',-123.456)
return render_template("filter.html",user=User1,mytime=mytime)
if __name__ == '__main__':
app.run()
filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过滤器</title>
</head>
<body>
<div>{{ mytime }}过滤后为{{ mytime|time_filter }}</div>
</body>
</html>
效果测试
控制语句
app.py
from flask import Flask,render_template,request
from datetime import datetime
app = Flask(__name__)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/control')
def control():
age=request.args.get('age')
age=int (age)
books=[{"name":"boo1",'price':12},{"name":"boo2",'price':18},{"name":"book3",'price':21}]
return render_template('control.html',age=age,books=books)
if __name__ == '__main__':
app.run()
control.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制语句</title>
</head>
<body>
<div>
{% if age>18 %}
<h2>可以进入网吧</h2>
{% elif age==18 %}
<h2>家长陪同下进入网吧</h2>
{% else %}
<h2>不可以进入网吧</h2>
{% endif %}
</div>
<div>
{% for book in books %}
<p>名称:{{ book.name }}</p>
<p>价格:{{ book.price }}</p>
{% endfor %}
</div>
</body>
</html>
效果测试
模板继承
模板继承是一项强大的功能,可减少代码重复并改善代码组织。 我们定义了一个基本模板,其他模板文件也从中继承。 这些模板文件将覆盖基本模板文件的特定块。
app.py
from flask import Flask,render_template,request
from datetime import datetime
app = Flask(__name__)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/base')
def base():
return render_template("base.html")
@app.route('/ch1')
def ch1():
return render_template("ch1.html")
@app.route('/ch2')
def ch2():
return render_template("ch2.html")
if __name__ == '__main__':
app.run()
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
ch1.html
{% extends "base.html" %}
{% block title %}
ch1的标题
{% endblock %}
{% block body %}
<div>ch1的body</div>
{% endblock %}
ch1.html
{% extends "base.html" %}
{% block title %}
ch2的标题
{% endblock %}
{% block body %}
<div>ch2的body</div>
{% endblock %}
加载静态文件
结构框架
add.py
from flask import Flask,render_template,request
from datetime import datetime
app = Flask(__name__)
class user:
def __init__(self,username,email):
self.username=username
self.email=email
@app.route('/')
def hello_world():
User=user('coleak','123@163.com')
person={
"username":"coleak",
"email":"123@666.com"
}
return render_template('index.html',user=User,person=person)
@app.route('/static')
def static_use():
return render_template("static.html")
if __name__ == '__main__':
app.run()
static.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>static</title>
<link rel="stylesheet" href="{{ url_for('static',filename=" rel="external nofollow" CSS/style.css") }}">
<script src="{{ url_for('static',filename="js/myjs.js") }}"></script>
</head>
<body>
<img src="{{ url_for('static',filename="images/flask.jpg") }}"></img>
</body>
</html>
myjs.js
alert('coleak');
style.css
body{
background-color: pink;
}
flask.jpg
效果测试
相关文章