Flask - Get clicked link info and display on rendered page

送分小仙女□ 提交于 2020-06-26 05:16:20

问题


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?


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/50426137/flask-get-clicked-link-info-and-display-on-rendered-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!