Flask:href链接到html不起作用

时间:2017-08-06 02:17:58

标签: python html flask

我有一个基本的Flask应用程序,其结构如下:

from flask import Flask
from flask import render_template
app = Flask(__name__,template_folder='E:\Programming\Python Projects\Flask')

@app.route('/')
def index():
    return render_template('hello.html')
@app.route('/route/')
def route1():
    return render_template('route1.html')
app.run(debug = True,port = 8080,host = '0.0.0.0')

hello.html:

<!DOCTYPE html>
<html>
<head>
    <title>Rendered!!</title>
</head>
<body>
<h1>
    The template has been rendered!!!<br>
    <a href="localhost:8080/route">Route No. 1</a>
</h1>
</body>
</html>

route1.html:

<!DOCTYPE html>
<html>
<head>
    <title>Route No. 1</title>
</head>
<body>
<h2>
    This is the first route!!!<br>
    Hello World!!!
</h2>
<iframe src="https://www.youtube.com/embed/YQHsXMglC9A" width="853" height="480" frameborder="0" allowfullscreen></iframe>
</body>
</html>

当我打开localhost:8080时,它运行正常。 但是,当我点击链接时,它会说:

The address wasn’t understood
Firefox doesn’t know how to open this address, because one of the following protocols (localhost) isn’t associated with any program or is not allowed in this context.

当我在地址栏中手动输入地址localhost:8080/route时,它可以正常工作。 此外,它在新选项卡中打开时工作正常。 我需要帮助!!! 谢谢!!!

1 个答案:

答案 0 :(得分:2)

您应该使用from flask import render_template, url_for

并在模板中:

<h1>
The template has been rendered!!!<br>
<a href="{{ url_for('route1') }}">Route No. 1</a>
</h1>

让Flask和Jinja2为你制作网址......

*您似乎忘记了链接上的尾部斜杠。  应该是localhost:8080 / route /  但是使用url_for会更好,因为它可以避免这种类型的问题