[英]Using render_template in Flask, how to split a string into multiple lines?
So, I'm messing around with the star wars swapi API, and rendering my api search onto an html file as a string, however I cannot seem to separate the titles in the string by line:因此,我正在使用星球大战 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)
Here is the HTML file:这是 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 %}
Here is the output: (on the index.html
page)这是输出:(在index.html
页面上)
"A New HopeAttack of the ClonesThe Phantom MenaceRevenge of the SithReturn of the JediThe Empire Strikes BackThe Force Awakens" (without the quotes) “克隆人的新希望进攻幻影的威胁西斯的复仇绝地归来帝国反击原力觉醒”(不带引号)
In HTML you have to use <br>
instead of \\n
to put text in new line.在 HTML 中,您必须使用<br>
而不是\\n
将文本放在新行中。
You should get titles as list and then use "<br>".join(titles)
您应该将标题作为列表,然后使用"<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)
Or you should send list with titles to template或者您应该将带有标题的列表发送到模板
result = []
for film in film_json['results']:
result.append( film['title'] )
return render_template('index.html', results=result)
and use {% for %}
loop in template并在模板中使用{% for %}
循环
<p>
{% for title in results %}
{{ title }}<br>
{% endfor %}
</p>
Eventually you should add '\\n'
to every title最终你应该在每个标题中添加'\\n'
for film in film_json['results']:
result += film['title'] + "\n"
return render_template('index.html', results=result)
and use <pre>
instead <p>
and it will respect "\\n"
(but it will use monospace font because it was created to display code - like this code in answer)并使用<pre>
代替<p>
并且它会尊重"\\n"
(但它会使用等宽字体,因为它是为了显示代码而创建的 - 就像这个代码的答案)
<pre>{{ result }}</pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.