【问题标题】:How to make "render_template" functional? [duplicate]如何使“render_template”功能化? [复制]
【发布时间】:2019-09-26 15:35:33
【问题描述】:

在我非常简单的 Flask 应用程序中,“rendare_template”不起作用。我需要设置、编码或从我的代码中删除什么?

main.py

import requests
from flask import (Blueprint, render_template, abort)
from flask import Flask
from jinja2 import TemplateNotFound
from flask import Flask
import simple_page
from simple_page import simple_page

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


if __name__ == '__main__':
    app.debug = True
    app.run(debug=True)

simple_page.py

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

simple_page = Blueprint('simple_page', __name__, template_folder='templates')

@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
    try:
        return render_template('pages/%s.html' % page)
    except TemplateNotFound:
        abort(404)

当我运行代码时,我得到:

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

【问题讨论】:

  • 您尝试访问的 URL 是什么?
  • @johnny243 我正在尝试访问127.0.0.1:5000/index,在我的模板文件夹中我有一个外部 index.html 文件。提前致谢。
  • 在下面查看我的答案。

标签: python flask visual-studio-code


【解决方案1】:

Flask 将在 templates 文件夹中查找模板。

...
return render_template('pages/%s.html' % page)

您应该在templates 文件夹中创建一个pages 文件夹并将您的模板移到那里。

所以当您访问http://127.0.0.1:5000/index 时,您的代码将在templates/pages 中查找index.html

更多信息请参见this

【讨论】:

  • 如果你看了你发给我的文章,你会发现没有一句与PAGES文件夹相关,谢谢先生。
  • 文档中没有提到pages 文件夹,但这是您在代码中添加的内容。这取决于你,如果你想以这种方式组织你的项目,它是有效的。
  • 我有一个类似的应用程序,主应用程序,我得到同样的错误,我没有页面文件夹,没关系,谢谢你先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2019-09-04
  • 2012-03-21
相关资源
最近更新 更多