在 python 中使用 Flask 时,我无法使 'extend' 功能正常工作

While using flask in python, I am not able to get the 'extend' feature to work properly

我是编程新手。我决定尝试使用 flask、python 和 HTML 创建一个网络应用程序。我设置了三个文件;两个 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 (main.py) 中 flask 应用程序的逻辑:

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 标签,其中包含短语 'information content'。

如有任何帮助,我们将不胜感激。

问题是{% 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 文件。