简体   繁体   English

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

[英]How to call a function/method on Flask from the template

First of all, I'm quite new using flask, but this is something I haven't been able to find so far. 首先,我对使用flask很陌生,但这是到目前为止我找不到的东西。

I'm working on my website with Flask and Jinja templates, using postgresql as a DB, I want to be able to call another function/method in my template. 我正在使用Flask和Jinja模板在我的网站上工作,使用postgresql作为数据库,我希望能够在模板中调用另一个函数/方法。

Here I can get all my shares (posts) 在这里,我可以获得所有股份(帖子)

@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)

template 模板

{% 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 %}

Basically, I want to be calling this function 基本上,我想调用此函数

def fetch_comments_by_shares(share_id):

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

    return comments

Thanks a lot. 非常感谢。

Instead of making multiple DB queries for each and every share id you can get all the comments for all the shares in the backend and then pass comments while rendering the template. 无需为每个共享ID进行多个数据库查询,您可以获取后端中所有共享的所有注释,然后在渲染模板时传递注释。 like. 喜欢。

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

and if still, you want to call the python function from jinja template then you can follow this answer for the same. 如果仍然要从jinja模板调用python函数,则可以按照此答案进行操作。 Call a python function from jinja2 从jinja2调用python函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM