0

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>
0

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, that did help, and seems much more useful! This is my first flask project, good to learn useful stuff in the beggining of the journey ;D
@dovexz12323 you are welcome. This is a standard way to render tempaltes. Take a look on this tutorial: digitalocean.com/community/tutorials/…. Good luck on your learning path!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.