Flask:带路径的render_template

问题描述 投票:3回答:2

我有几个不同的模板,我正在尝试用于我的烧瓶应用程序。

我尝试过以下但它似乎只是直接在/ templates内部而不是/ templates / folder1,templates / folder2等。

 return render_template('index.html', template_folder='folder1')
 return render_template('folder1/index.html')

两者都没有按预期工作,我如何指定不同模板的子文件夹。

flask
2个回答
-4
投票

我认为肖恩是对的,但也有:你试过双引号吗?我正在使用Blueprint,所以可能会有所不同,但这就是我的看法:

return render_template("users/register.html")

所以你的可能是:

return render_template("folder1/index.html")

5
投票

创建Flask应用程序(或蓝图)时可以指定模板文件夹:

from flask import Flask
app = Flask(__name__, template_folder='folder1')

资料来源:http://flask.pocoo.org/docs/0.12/api/#application-object

from flask import Blueprint
auth_blueprint = Blueprint('auth', __name__, template_folder='folder1')

资料来源:http://flask.pocoo.org/docs/0.12/blueprints/#templates

template_folder与app / blueprint所在的位置相关。使用os库创建app / blueprint目录之外的模板文件夹的路径。

例如。

import os
APP_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(APP_PATH, 'templates/')
  • 从app root的子目录运行
  • APP_PATH检索父目录路径(app root)
© www.soinside.com 2019 - 2024. All rights reserved.