Reputation: 21
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:
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:
{% 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)
"A New HopeAttack of the ClonesThe Phantom MenaceRevenge of the SithReturn of the JediThe Empire Strikes BackThe Force Awakens" (without the quotes)
Upvotes: 2
Views: 1910
Reputation: 142889
In HTML you have to use <br>
instead of \n
to put text in new line.
You should get titles as list and then use "<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
<p>
{% for title in results %}
{{ title }}<br>
{% endfor %}
</p>
Eventually you should add '\n'
to every title
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>{{ result }}</pre>
Upvotes: 2