I have a list with the name of colors:
colors = [red, green, blue]
And I want it to be printed out on my web page as
- red
- green
- blue
I tried this by using an argument in my HTML template {{colors_out}}
, where I pass a string with "\n"
to it as follows:
colors_out = ""
for i in range(len(colors)):
colors_out = (str(i) ". " colors[i] "\n")
However, that does nothing but add a space between my colors. It prints out these:
0. red 1. green 2. blue
instead of my desired format. I tried replacing "n"
with "<br>"
in the for loop above too, but then it will result in:
0. red<br>1. green<br>2. blue<br>
CodePudding user response:
One way, which you can try to use a for loop in Jinja2 in your HTML.
You can simply pass a list to the HTML and then use for loop in Jinja2 along with the
tags to print the outputs on seperate lines -
For example in your case -
In your Flask code -
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/colors', methods=["GET","POST"])
def test():
#your other code
colors = ['red', 'green', 'blue']
return render_template('index.html',color=colors)
if __name__ == '__main__':
app.run()
And your HTML code -
just add this for loop, where i iterates over all the colors and print them in seperate lines
{% for i in color %}
<p>{{ i }} </p>
{% endfor %}
you can also use any other tag as per your requirement, it will still print on new line.