bestallen 2019-11-04
Django框架有自己独立的模板系统,而Flask是没有的,Flask默认采用jinjia2模板系统,jinjia2是仿写Django模板系统的一个第三方模块,在安装Flask的时候,jinjia2被以依赖包的形式安装到了环境里,下面介绍在Flask中模板渲染的步骤:
Flask中使用render_template方法来加载HTML文件,HTML默认指向当前脚本同级目录templates下的文件
from flask import Flask
from flask import render_template
# 创建一个应用
app = Flask(__name__)
@app.route("/index/", methods=["GET", "POST"])
def index():
return render_template("index.html")
if __name__ == ‘__main__‘:
app.run(host="127.0.0.1", port=5000, debug=True)使用render_template方法前需要从flask将该方法导入,看下方源代码,template_folder参数的默认值为"templates",当浏览器访问路由"http://127.0.0.1:5000/index/"时,视图函数将返回脚本同级目录templates下的index.html文件,
def __init__(
self,
import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
instance_relative_config=False,
root_path=None,
):a、常规传参
@app.route("/index/", methods=["GET", "POST"])
def index():
return render_template("index.html", name = "index")b、解包传参
@app.route("/index/", methods=["GET", "POST"])
def index():
name = "index"
return render_template("index.html", **locals())<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
这是一个{{name}}文件
</body>
</html>前端页面接收后台传递变量的方式与Django模板系统一致
效果展示:

静态文件指的是js文件、css文件、image图片等,在Flask当中,静态文件默认放在脚本同级的static目录下,如下源码所示,static_folder参数的默认值为"static"
def __init__(
self,
import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
instance_relative_config=False,
root_path=None,
):在原来静态文件路径的基础上在路径开头加上"/static/"
<link rel="shortcut icon" type="image/x-icon" href="/static/img/common/icon/ome.icon.linklogo.png">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" href="/static/css/iconfont.css" />
<link rel="stylesheet" href="/static/css/ome.style.css" />
<link rel="stylesheet" href="/static/css/ome.style.dif.css" />
<link rel="stylesheet" href="/static/css/ome.index.css" />