Flask 应用程序将 SQL 数据库中的项目列表显示为文本

Flask application displaying list of items from SQL database as text

我正在尝试在我的 Flask 应用程序中显示数据库中的项目列表。不幸的是,列表元素作为文本而不是 HTML 代码放置在 HTML 中,我做错了什么以及如何防止这种情况发生?

我的路由函数:

@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

我的index.html:

<!DOCTYPE html>
<html>
    <body>
        <div class = item>
            {{ products }}
        </div>
    </body>
</html>

您最好将产品作为列表传递给模板:

@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

然后像那样渲染模板

<!DOCTYPE html>
<html>
    <body>
        <div class = item>
            <ul>
                {% for product in products %}
                    <li>{{product.title}}, {{product.price}}</li>
                {% endfor %}
            </ul>
        </div>
    </body>
</html>