![](/img/trans.png)
[英]how to pass parameter from POST method and do function call in flask?
[英]How to call a function/method on Flask from the template
首先,我對使用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
非常感謝。
無需為每個共享ID進行多個數據庫查詢,您可以獲取后端中所有共享的所有注釋,然后在渲染模板時傳遞注釋。 喜歡。
render_template('shares.html', form=form, shares=shares, comments=comments)
如果仍然要從jinja模板調用python函數,則可以按照此答案進行操作。 從jinja2調用python函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.