【问题标题】:Is using database queries inside a jinja2 template a good practice?在 jinja2 模板中使用数据库查询是一种好习惯吗?
【发布时间】:2019-12-09 17:29:56
【问题描述】:

我想知道是否可以在模板中使用数据库查询,例如,像这样:

{% for thread in threads %}
<div class="thread">
    <div class="thread__op">
        {% with opening = thread.posts.first() %} {# thread.posts.first() is a query. #}
        {{ opening.title }}
        {{ opening.message }}
        {% endwith %}
    </div>
</div>
{% endfor %}

【问题讨论】:

    标签: python flask jinja2 flask-sqlalchemy


    【解决方案1】:

    我建议不要这样做,因为您不想将查询传递给您的模板。我建议您只在服务器端从您的查询中创建一个字典列表:

    openings = [{'title': 'title1', 'message': 'message1'},...]

    然后您可以使用以下方法将其传递给您的模板:

    return render_template('page.html', openings=json.dumps(openings))

    然后您可以像上面那样简单地遍历您的开口,除非您不需要{% with opening = thread.posts.first() %}。所以应该是:

    {% for opening in openings %}
    <div class="thread">
        <div class="thread__op">
            {{ opening.title }}
            {{ opening.message }}
        </div>
    </div>
    {% endfor %}
    

    一般来说,最好让您传递到模板中的数据尽可能简单。如果您要在服务器端工作,最好将其传递到您的页面时尽可能简单。

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多