bordax
bordax

Reputation: 87

Flask template executes HTML onclick function on page load

My template renders multiple cards to page and I want each card to have "Add to favorites" button to save cards information to DB as object. The problem is when I reload page it executes function for all items and doesn't respond to click at all.

cards.html https://codepen.io/bordax/pen/YzWWQrb

app.py

def add_to_favorites(item):
    print(item['name'])

@app.route("/favorites")
def favorites():
    # Array of objects
    data = info_filter(food_data)

    return render_template("cards.html", data=data, add=add_to_favorites)

Upvotes: 0

Views: 315

Answers (1)

BrenBarn
BrenBarn

Reputation: 251538

When you use {{ stuff }} in your template, stuff will be executed by Flask as part of building the page. Filling in the template by evaluating {{ }} blocks happens on the server side before the browser ever sees the page. Contrariwise, by the time the user is clicking on something on the web page, Flask is out of the picture and knows nothing about such clicks, unless the web page explicitly does something to notify the server.

Sadly, if you want to respond to browser events like clicks, you'll have to write JavaScript code, and have that code communicate with your Flask backend (e.g. by sending HTTP requests).

Upvotes: 1

Related Questions