I am trying to display a list of my items from the database in my flask application. Unfortunately, the list elements are placed into the HTML as text, instead of HTML code, what am I doing wrong and how to prevent this from happening?
My route function:
@app.route('/')
def index():
try:
products = Product.query.all()
product_text = '<ul>'
for product in products:
product_text = '<li>' product.title ', ' product.price '</li>'
product_text = '</ul>'
return render_template('index.html', products=product_text)
except Exception as e:
error_text = "<p>The error:<br>" str(e) "</p>"
hed = '<h1>Something is broken.</h1>'
return hed error_text
my index.html:
<!DOCTYPE html>
<html>
<body>
<div class = item>
{{ products }}
</div>
</body>
</html>
CodePudding user response:
You would better to pass products to template as a list:
@app.route('/')
def index():
try:
products = Product.query.all()
return render_template('index.html', products=products)
except Exception as e:
error_text = "<p>The error:<br>" str(e) "</p>"
hed = '<h1>Something is broken.</h1>'
return hed error_text
and then render template like that
<!DOCTYPE html>
<html>
<body>
<div class = item>
<ul>
{% for product in products %}
<li>{{product.title}}, {{product.price}}</li>
{% endfor %}
</ul>
</div>
</body>
</html>