简体   繁体   中英

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?

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)

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