如何让jinja2显示不同选项的不同div被选中

How to make jinja 2 display different divs if different options are selected

{% extends "main.html" %}
{% block content %}
<h2> Please select a sector you would like to iterate through:</h2>
<br />
<form method="POST" action="">
<input type="text" name="statement" />
<input type="submit" />
Do you wish the output to be sorted?:
<select>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</form>
{% if request.args.get['yes'] %}
dfghjhkl;nbovicudhbnrfmg,hklbjuvhcndmf,
{% elif request.args.get['no'] %}
12345676434565456765456
{% endif %}
{% endblock %}

我想要的是根据在选项中选择的内容显示不同的信息。我刚开始接触 Flask 和 Jinja2,所以我对这种编码不是很熟悉。

如果您的表单使用“POST”方法,那么您必须检查 request.form 而不是 request.args。来自文档:

form

A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.

args

A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

我想您必须将表单方法更改为“GET”或更改模板代码以使用 request.form

此外,我的 Flask 有点生锈,但我认为它是 request.args.get('yes')request.args['yes'] 而不是 request.args.get['yes']

你的问题不太清楚。你想让它动态发生吗?如果是这样,那么您将不得不在前端使用 JavaScript。

<div id="output"></div>
<script type="text/javascript">
$('#myselect').on('change', function() {
  var selected = $( "#myselect option:selected" ).text();
  if(selected == "yes") $("#output").html("dfghjhkl;nbovicudhbnrfmg,hklbjuvhcndmf,");
  else $("#output").html("12345676434565456765456");
});
</script>

如果您想提交它并获得不同的页面,请将表单的操作更改为 GET 并创建一个路由到 return 您的模板和 action 到一个路由会做这样的事情:

@app.route("/yourform/getinfo")
def show_sorted_info():
  return render_template("results.html")

results.html 的模板如下:

{% if request.args.get('yes') %}
  dfghjhkl;nbovicudhbnrfmg,hklbjuvhcndmf,
{% elif request.args.get('no') %}
  12345676434565456765456
{% else %}
  no option selected.
{% endif %}