【问题标题】:Flask: render_template with path烧瓶:带有路径的render_template
【发布时间】:2014-02-13 21:18:32
【问题描述】:

我尝试将几个不同的模板用于我的烧瓶应用程序。

我尝试了以下方法,但它似乎只能直接查看 /templates 内部,而不是 /templates/folder1、templates/folder2 等。

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

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

【问题讨论】:

  • 第二个应该可以正常工作 - 你的目录结构是什么样的?
  • 在模板文件夹内我有 folder1 包含 index.html 和 folder2 包含 index2.html

标签: flask


【解决方案1】:

模板文件夹可以在创建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 相对于应用程序/蓝图所在的位置。 使用 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_PATH 检索父目录路径(应用根目录)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我认为 Sean 是对的,而且:你试过双引号吗?我使用的是蓝图,所以可能会有所不同,但这是我的样子:

      return render_template("users/register.html")
      

      所以你的可能是:

      return render_template("folder1/index.html")
      

      【讨论】:

      • 单引号、双引号或三引号……它们都是字符串,所以没有区别。 :-)
      • 没关系我使用的是 index2.html 而不是 index.html
      • 这个答案不正确,问题仍然需要一个有效的答案作为参考。
      • 这不能回答问题
      • 单引号和双引号一样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2020-08-15
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多