简体   繁体   中英

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.

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.

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. 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. Call a python function from jinja2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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