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)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值