所以,我正在摆弄星球大战 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/