如何将变量从html传递到后端烧瓶

问题描述 投票:0回答:1

有这么多带有标签的td元素,我想知道用户单击了哪个元素,并且我想从html传递到后端,并在后端对用户的选择进行处理;

这是我的html;

<a href="/selected" ????><td>{{ options1 }}</td></a>
<a href="/selected"><td>{{ options2 }}</td></a>
<a href="/selected"><td>{{ options3 }}</td></a>
<a href="/selected"><td>{{ options4 }}</td></a>
<a href="/selected"><td>{{ options5 }}</td></a>
<a href="/selected"><td>{{ options6 }}</td></a>

当用户单击一个时,我想将其发送到后端;

@app.route('/selected', methods=['GET', 'POST'])
def selected():
selected_option = request.args.get('????')
return render_template("selected.html", selected_option=selected_option)

我如何填写问号?

url flask request selecteditem choice
1个回答
0
投票

由于一些原因,options1options2等具有单独的变量可能使这很麻烦:

  • 您需要手动更新模板的硬编码以添加更多选项。
  • 每个选项的URL部分,可能与链接文本不同。

您可能希望在字典中定义选项:

sections = {'first-option': 'I am the first option',
            'second-option': 'Click me for fun and profit',
            'third-option': 'All flights have been cancelled',
           }

现在将在生成链接栏的页面上,如果您将其传递给:

return render_template('some_page.html', SECTIONS=sections)

然后您可以执行以下操作:

{% for key, value in SECTIONS.items() %}
  <a href="{{url_for('selected', section=key)}}">{{value}}</a>
{% endfor %}

这将自动生成与以下视图功能兼容的正确URL:

@app.route('/selected/<section>')
def selected(section):
    # Assuming the first URL:
    print (section) # 'first-option'
    print (sections[section]) # 'I am the first option'

    return render_template("selected.html", selected_option=section)

您可能还希望看看this gist,它将使概念更进一步。

这还使用上下文处理器将SECTIONS变量插入所有页面,而不是将其传递给各个render_template函数。

© www.soinside.com 2019 - 2024. All rights reserved.