python - 在Flask中使用render_template,如何将字符串拆分为多行?

标签 python string api flask

所以,我正在摆弄星球大战 Swapi API,并将我的 api 搜索作为字符串呈现到 html 文件上,但是我似乎无法按行分隔字符串中的标题:

from flask import Flask, render_template, request, redirect
import requests
import json
import swapi

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    url = "https://swapi.co/api/"
    star_wars_api = requests.get(url)

    result = ''
    if request.method == 'POST':
        films = requests.get(star_wars_api.json()['films'])
        if films.status_code == 200:
            if request.form['search'] == "films":
                film_json = films.json()

                for film in film_json['results']:
                    result += str(film['title'])

                return render_template('index.html', results=result)
    else:
        return render_template('index.html')


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

这是 HTML 文件:

{% extends 'base.html'%}

{% block head %} {% endblock %}

{% block body %}

<form action="/" method="POST">
    <label for="search">Search:</label>
    <input class="form-control" type="text" name="search" id="search" placeholder="Search" aria-label="Search">
    <br>
    <input type="submit" value="Post">
</form>

<p> {{ results }}</p>

{% endblock %}

以下是输出:(在 index.html 页面上)

“新希望克隆人的进攻幽灵的威胁西斯的复仇绝地归来帝国反击原力觉醒”(不带引号)

最佳答案

在 HTML 中,您必须使用 <br>而不是\n将文本放入新行。

您应该获取标题作为列表,然后使用 "<br>".join(titles)

titles = []

for film in film_json['results']:
    titles.append( film['title'] )

result = "<br>".join(titles)

return render_template('index.html', results=result)

或者您应该将带有标题的列表发送到模板

result = []

for film in film_json['results']:
    result.append( film['title'] )

return render_template('index.html', results=result)

并使用{% for %}模板中的循环

<p>
{% for title in results %} 
{{ title }}<br>
{% endfor %}
</p>

最终你应该添加'\n'每个标题

for film in film_json['results']:
    result += film['title'] + "\n"

return render_template('index.html', results=result)

并使用<pre>相反 <p>它会尊重 "\n" (但它将使用等宽字体,因为它是为了显示代码而创建的 - 就像答案中的代码一样)

<pre>{{ result }}</pre>

关于python - 在Flask中使用render_template,如何将字符串拆分为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59350315/

相关文章:

r - 在字符串中的特定位置插入空格

api - Youtube 数据 API 版本 3 分页

python - 与 Flask 上的 REST 的概念差异

python - 是否可以将单一回归技术应用于具有不同模式的数据?

python - 为什么在 python 中使用套接字嗅探 wifi 帧时我得到以太网帧(不是 802.11)

python - 关于使用 xhtml2pdf 从网站解析 css 的问题

C - 有没有办法用 'Enter' 以外的键终止字符串输入?

c++ - 如何防止用户读取存储在二进制文件中的字符串?

python - Pastebin API : Getting Unlisted Paste Always

python - 如何自动创建第二个变量?