How do I get the text of a clicked link into an app.route function?
Eg: say I have a list of links displayed all of which link to the same url but load different content each.
<li><a href="/animals">cat</a></li>
<li><a href="/animals">dog</a></li>
<li><a href="/animals">dragon</a></li>
When I click 'cat' I need to retrieve the word 'cat' along with rendering template for /animals
@app.route('/animals', methods=['GET', 'POST'])
def animals():
selected_animal = get_clicked_animal_name_from_previous_page()
return render_template(animals.html', title='Animal Details', animal=selected_animal)
Is a function like get_clicked_animal_name_from_previous_page() possible?
How do you display Python output on a Flask HTML page? Create a simple HTML page to display text. create a route ”/” and return home. html from the function.
You can use AJAX to post form data, generate html in flask, pass it as AJAX result and update your page with it via javascript. $. ajax({ type: 'POST', url: '/result', data: JSON.
You can pass argument via request.args like this:
<li><a href="{{url_for('animals', type='cat')}}">cat</a></li>
<li><a href="{{url_for('animals', type='dog')}}">dog</a></li>
<li><a href="{{url_for('animals', type='dragon')}}">dragon</a></li>
And receive it like this:
@app.route('/animals', methods=['GET', 'POST'])
def animals():
selected_animal = request.args.get('type')
print(selected_animal) # <-- should print 'cat', 'dog', or 'dragon'
return render_template(animals.html, title='Animal Details', animal=selected_animal)
You can slightly change your href
for each animal
to redirect to an animals/<animal>
route. This way,<animal_type>
will be passed to the route function to be used later:
<li><a href="/animals/cat">cat</a></li>
<li><a href="/animals/dog">dog</a></li>
<li><a href="/animals/dragon">dragon</a></li>
Then, in the app:
@app.route('/animals/<animal>', methods=['GET'])
def animals(animal):
return render_template('animals.html', title='Animal Details', animal=animal)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With