python - 如何从模板调用 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 函数
推荐阅读
- reactjs - 任务“:react-native-music-control:compileDebugJavaWithJavac”执行失败
- php - For循环计算多条记录
- macos - 法新社和 Time Machine 停止在 QNAP HS-251+ 上工作
- html - 使用 re 在 html 文本中返回 html 标签
- javascript - 仅使用 ObjectID 在 MongoDB 中设置关系
- python - 如何从列表列表中制作字典
- html - HTML 属性中是否允许使用 html 代码?
- r - 如何使用模拟数据运行逻辑回归{数据在 1 个 CSV 文件中有 50 个观察值和 100 个模拟}
- ios - 自定义更改单元格底部边框的颜色
- python - 气流和模块