Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Get clicked link info and display on rendered page

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?

like image 241
Jay Avatar asked May 19 '18 14:05

Jay


People also ask

How do you display Python output on a flask html page?

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.

How do you post the output result on the same page on the flask app?

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.


2 Answers

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)
like image 108
Ali Yılmaz Avatar answered Oct 25 '22 08:10

Ali Yılmaz


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)
like image 1
Ajax1234 Avatar answered Oct 25 '22 09:10

Ajax1234