Flask-获取点击的链接信息并显示在渲染页面上 [英] Flask - Get clicked link info and display on rendered page

查看:122
本文介绍了Flask-获取点击的链接信息并显示在渲染页面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将单击链接的文本输入到app.route函数中?

How do I get the text of a clicked link into an app.route function?

例如:说我有一个显示了所有链接的链接列表,这些链接都指向相同的url,但是每个链接都加载不同的内容.

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)

像get_clicked_animal_name_from_previous_page()这样的函数可以吗?

Is a function like get_clicked_animal_name_from_previous_page() possible?

推荐答案

您可以通过 request.args 传递参数,如下所示:

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>

并像这样接收它:

@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)

这篇关于Flask-获取点击的链接信息并显示在渲染页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆