【问题标题】:Flask: How to output string from Python but displayed as hyperlinks in HTMLFlask:如何从 Python 输出字符串但在 HTML 中显示为超链接
【发布时间】:2020-03-14 00:41:00
【问题描述】:

所以,我从 HTML 文本框中获取用户输入,然后返回一些 url。但是目前,当我直接返回 URL(以字符串形式)时,HTML url 输出不可点击;它们只是纯文本。有没有办法将返回的 python 字符串转换为 HTML url?

我可以将 python 端返回的 url 的格式更改为可以转换为可点击的 HTML url 的任何内容。

Python 代码:

#this gets the query and then returns urls
@app.route('/output', methods=['POST'])
def output():
    query_list = request.form['query']
    outputResults = someFunction(query_list)
    return render_template("output.html", output=outputResults)

HTML 代码:

{% extends 'layout.html' %}

{% block body %}
<div class="jumbotron text-left">
  <body>
    <style> p {white-space: pre-wrap; }</style>
    <h1>Output</h1>
    <p> {{output}}
    </p>
  </body>

  </div>
{% endblock %}  

谢谢

【问题讨论】:

  • 如果你的输出是像http://www.something.com这样的链接,你应该在你的模板中添加锚标记,例如:&lt;a href="{{output}}"&gt;link title&lt;/a&gt;
  • @dhentris 如果我有一个未知数量的要输出的链接列表怎么办?

标签: python-3.x url flask


【解决方案1】:

如果您的查询中有多个链接,请在模板中使用 for 循环,如下所示:

{% extends 'layout.html' %}

{% block body %}
<div class="jumbotron text-left">
  <body>
    <style> p {white-space: pre-wrap; }</style>
    <h1>Output</h1>
    {% for link in output %}
     <a href ="{{link}}">title_your_link</a>
    {% endfor %}
  </body>
  </div>
{% endblock %}

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 2018-09-25
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多