Flask:如何返回模板目录之外的网站

2024-09-28 22:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图返回网站(html文件)以外的模板目录

.py文件的目录:

archiv/archiv/web/article/articles.py

html的目录:

instance/articles/private/abc/abc.html

我的文章.py代码:

from flask import Blueprint, render_template
bp = Blueprint('articles', __name__, url_prefix='/articles')

@bp.route('/<article>')
def show_article(article):
    """Show a article."""
    base_url = '/instance/articles/private/'
    url_to_return = base_url + str(article) + '/' + str(article) + '.html'
    # return render_template(url_to_return)
    return "Hello " + article

该路线被访问,但一旦我试图返回网站(评论),我不工作->;找不到模板。我很确定渲染模板不是´不是路要走,但我没有´我没找到合适的

有人能告诉我如何返回网站abc.html一旦路线被调用

提前多谢


Tags: 文件instancepy目录模板urlreturn网站
1条回答
网友
1楼 · 发布于 2024-09-28 22:18:41

您可以在创建蓝图时添加新的模板目录。当您将模板名称传递给render_template函数时,它还会检查新位置

from flask import Flask, Blueprint, render_template

bp = Blueprint(
    'articles',
    __name__,
    url_prefix='/articles',
    template_folder="../instance", # New line!
)

@bp.route('/<article>')
def show_article(article):
    """Show a article."""
    return render_template("articles/private/abc.html")

app = Flask(__name__)
app.register_blueprint(bp)

来自烧瓶documentation(用于蓝图)

template_folder – A folder with templates that should be added to the app’s template search path. The path is relative to the blueprint’s root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app’s templates folder.

如果要将模板目录添加到整个应用程序,可以在创建Flask实例时设置template_name。查看this了解更多信息

相关问题 更多 >