【问题标题】:While using flask in python, I am not able to get the 'extend' feature to work properly在 python 中使用烧瓶时,我无法让“扩展”功能正常工作
【发布时间】:2018-02-02 23:25:18
【问题描述】:

我是编程新手。我决定尝试使用烧瓶、python 和 HTML 创建一个 Web 应用程序。我设置了三个文件;两个 HTML 和一个 python:

这是应该替换信息的 HTML 文件 (didntwork.html):

<!doctype html>
<html>
  <head>
    <title>My Webpage</title>
  </head>
  <body>
      <h3>Information:</h3>
      {% block body %}{% endblock %}
  </body>
</html>
                                        .

这是应该向第一个(connection.html)输入信息的文件:

{% extends 'didntwork.html' %}
{% block body %}
<h4>information content</h4>
{% endblock %}
                                        .

最后,这是python中flask应用的逻辑(main.py):

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('didntwork.html')


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

不幸的是,第二个 HTML 文件中的extends 似乎无法识别,并且其块中的信息不会在第一个 HTML 文件中被替换(didntwork.html)。

这是输出:

预期结果应在正文中附加一个带有“信息内容”短语的 h4 标记。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python html flask frontend web-frontend


    【解决方案1】:

    问题是{% extends 'didntwork.html' %}。据我所知,包含此代码的文件:

    <!doctype html>
    <html>
      <head>
        <title>My Webpage</title>
      </head>
    <body>
      <h3>Information:</h3>
      {% block body %}{% endblock %}
    </body>
    </html>
    

    是您的 connection.html 文件。

    您正在扩展至您正在渲染的同一文件 (didntwork.html)。您必须更改 extends 行以扩展您的基本 html,在这种情况下为 connection.html

    在您的didntwork.html 中使用此代码:

    {% extends 'connection.html' %}
    {% block body %}
    <h4>information content</h4>
    {% endblock %}
    

    您可以在Template Inheritance找到更多信息

    基于澄清更新

    您在 route 中呈现了错误的文件。 您应该渲染connection.html,这将扩展您的didntwork.html 文件。

    【讨论】:

    • 对不起,这些文件在我的原始帖子中没有命名,这可能会产生误导;我已经用适当的文件名对其进行了编辑。
    • 抱歉,您不小心混淆了文件名。感谢您的回复,但添加您提供的代码会导致RecursionError
    • 根据您的说明更新了我的答案。试试看,让我知道
    • 我尝试将main.py 中的路线更新为return render_template('connection.html'),但是该元素仍然没有附加,只是像以前一样显示“信息:”。我应该发布一个main.py.looks like now 的 imgur 链接吗?
    • 谢谢!重新启动服务器工作。我已将您的答案标记为正确。
    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多