首页 > 解决方案 > 如何从模板调用 Flask 上的函数/方法

问题描述

首先,我是使用烧瓶的新手,但这是我迄今为止无法找到的东西。

我正在使用 Flask 和 Jinja 模板在我的网站上工作,使用 postgresql 作为数据库,我希望能够在我的模板中调用另一个函数/方法。

在这里我可以得到我所有的分享(帖子)

@shares_app.route('/shares', methods=['GET'])
@login_required
def last_shares():

    shares = fetch_last_shares()
    form = ReusableForm(request.form)
    return render_template('shares.html', form=form, shares=shares)

模板

{% for share in shares %}
<li class="comment"  style="border:1px solid black; padding:5px;" >
<a class="pull-left" href="#">
    <img width="35" height="35" avatar="{{share[5]}}">
</a>
<div class="comment-body">
    <div class="comment-heading">
        <h4 class="user">{{share[5]}} ({{share[4]}}) </h4>
        <h5 class="time">{{share[3]}} /</h5>
    </div>
    <p> <b>{{share[0]}} </b> / {{share[2]}}</p>
</div>
<!--comments here -->
    Here I wanna be able to get all my comments related to shares, here its where I\'m no sure if  I can call another function from my controller.
    comments = fetch_last_comments(share[0])
    {% for comment in comments %}
    Show comments here 
    {% endfor %}
<!--comments here -->

{% endfor %}

基本上,我想调用这个函数

def fetch_comments_by_shares(share_id):

    comments = db.query("""SELECT * FROM comments WHERE share_id = {} """.format(share_id)).getresult()

    return comments

非常感谢。

标签: pythonpython-3.xflaskflask-wtforms

解决方案


您可以在后端获取所有共享的所有评论,然后在渲染模板时传递评论,而不是为每个共享 ID 进行多个数据库查询。喜欢。

render_template('shares.html', form=form, shares=shares, comments=comments)

如果仍然如此,你想从 jinja 模板调用 python 函数,那么你可以按照这个答案来做同样的事情。 从 jinja2 调用 python 函数


推荐阅读