Flask:带路径的render_template

时间:2014-02-13 21:18:32

标签: flask

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

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

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

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

确保Python文件和Template文件夹都在同一工作目录文件夹下。

答案 2 :(得分:-4)

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

return render_template("users/register.html")

所以你的可能是:

return render_template("folder1/index.html")