如何从模板调用Flask上的函数/方法



首先,我对使用flask很陌生,但这是我迄今为止还没能找到的东西。

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

在这里我可以得到我所有的股票(帖子(

@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

非常感谢。

您可以在后台获取所有共享的所有注释,然后在呈现模板时传递注释,而不是对每个共享id进行多个DB查询。喜欢

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

如果仍然想从jinja模板调用python函数,那么可以按照这个答案进行操作。从jinja2 调用python函数

最新更新