原创

Flask(4)-Jinja2模板使用(路径)

  • templates文件夹是专门用来存放模板文件的(网页文件,html)

# 在templates目录下创建index.html文件
# index.html文件
<!DOCTYPE html>
<html lang="zh-en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>index</title>
</head>
<body>
<h1>Index</h1>
</body>
</html>
# app.py代码

# 导入render_template包
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/index/")
def index():
    # 返回页面
    return render_template("index.html")

if __name__ == '__main__':
    app.run(debug=True)
  • 如果在template文件夹下面有个子文件夹怎么调用呢??

# templates/home/intex2.html

<!DOCTYPE html>
<html lang="zh-en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>intex2</title>
</head>
<body>
<h1>intex2</h1>
</body>
</html>
# app.py

from flask import Flask, render_template


app = Flask(__name__)


@app.route("/index2/")
def index2():
    return render_template("home/index2.html")

if __name__ == '__main__':
    app.run(debug=True)


# 访问http://127.0.0.1:5000/index2/
  • 修改模板存放路径

# app.py

from flask import Flask, render_template

# 指定模板路径
# 在__name__后面加上, template_folder="D:/templates",修改存放路径
app = Flask(__name__, template_folder="D:/templates")

@app.route('/')
def hello_world():
    return '<h1 style="color:red">Hello World!</h1>'

@app.route("/index/")
def index():
    return render_template("index.html")

@app.route("/index2/")
def index2():
    return render_template("home/index2.html")

if __name__ == '__main__':
    app.run(debug=True)

 

正文到此结束
评论

登录后才能发表评论 登录/注册

0评论
  • 还没有评论,快来抢沙发吧!