模板文件
我们每个路由返回的是一个html,但是在python内部写上一堆html并不好玩,所以这时候就需要render_template来渲染模板文件,模板文件在templates文件夹中,目前目录结构为:
- templates
- index.html
- app.py
index.html放入我们需要返回的html:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>Hello World!</p>
</body>
</html>
app.py引入render_template函数:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
加入http://127.0.0.1:5000/,我们依旧看到了那熟悉的Hello World!:
解析
接下来我们来看看render_template函数:
return render_template("index.html")
render_template会在templates文件夹中寻找模板文件,因此路径不需要写成templates/index.html
。
现在你可以任意更改html文件并查看效果。
Jinja2模板
当然这个html文件可不是简单的html文件,你可以在里面嵌入python代码和变量,这就是Jinja2模板的威力了,以下是常见的嵌入方式:
- {% python代码 %}
- {{ python变量 }}
- {# 注释 #}
以下给两个例子,我相信你会理解更透彻,当然下面的这些不是全部,首先更改目录结构为:
- static
- test.jpg
- templates
- index.html
- app.py
index.html先使用简单的双大括号嵌入变量:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
{{ msg }}
<img src="{{ url_for('static', filename='test.jpg') }}">
</body>
</html>
app.py中的render_template时附带这个msg参数:
#app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html", msg="Hello World!")
if __name__ == "__main__":
app.run(debug=True)
你会看到:
我们可以看到{{ msg }}
被替换为Hello World!
了,之后我们会介绍更多模板文件的用法。