渲染模板
Flask使用了一个名为Jinja2的强大模板引擎。
templates/index.html
<h1>Hello, world!</h1>
templates/user.html
<h1>Hello, {{ name }}!</h1>
{{ name }}结构表示一个变量,它告诉模板引擎这个位置的值可以从模板渲染时使用的数据中获取
在渲染模板之前需要把index.html和user.html存放在根目录下的templates文件夹下,如果没有就创建一个
还需要在python里导入模块,render_template
hello.py 渲染模板
from flask import Flask, render_template
app = Flask(__name__)
# 首页
@app.route('/')
def index():
return 'Hello ,world!'
# 动态URL规则
@app.route('/user/<name>')
def user(name):
return "Hello, %s" % name
# 渲染模板
@app.route('/template/hello/')
def hello():
return render_template('index.html')
@app.route('/template/<name>')
def template_user(name):
return render_template('user.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
运行程序后在浏览器里分别输入http://127.0.0.1:5000/template/hello/和http://127.0.0.1:5000/template/Flask
变量过滤器
就说几个常用的
capitalize 把值的首字母转换成大写,其他字母转化成小写
title 把值中每个单词的首字母都转换成大写
条件控制语句
<h1>{% if name %}
Hello, {{ name }}!
{% else %}
Hello, flask!
{% endif %}!
</h1>
模板继承
基模板base.html
templates/base.html
<html>
<head>
{% block head %}
<title>
{% block title %}{% endblock %} - My application
</title>
</head>
{% endblock%}
</html>
调用基模板
templates/user.html
{% extends "base.html" %}
{% block title %}aaa{% endblock %}