Flask:如何通过单击链接更改html中Flask变量的值

2024-09-28 22:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改flask变量的值

当用户单击链接时

诸如此类

(我试过这种方法,但其中一种不起作用)

<a href="#" onclick=" {% set data = true %}">sutfile</a>

因为稍后我有下面的循环,我想填充select标记

仅当布尔值=true时

<label>vCenterAddress:<select> {% if data == true %} {% for a in vCenterAddress %} <option value="">{{ a[0] }}</option> {% endfor %} {% endif %}</select></label>

route.py中的布尔过程

@app.route("/", methods=['GET', 'POST'])

    def index():
        cur = mysql.connection.cursor()
        vCenterAddress = cur.execute(f"SELECT DISTINCT vCenterAddress FROM linux0 where vCenterAddress <> \"None\" ")
        vCenterAddress = cur.fetchall()
        data_to_show: bool = False
        return render_template('index.html', vCenterAddress=vCenterAddress, data=data_to_show)

Tags: to方法用户trueflaskdataindex链接
2条回答

下面是我在评论中建议的更详细的解释

  1. 更改链接的href:
<!  when a user clicks this it will load yourpage.com?show_data=true  >
<a href="?show_data=true">sutfile</a>
  1. 获取您在flask中定义的参数
## you need flask's request module to access the request parameters
from flask import request

@app.route("/", methods=['GET', 'POST'])
def index():
   # this will be False by default, and True if the show_data url parameter is "true"
   show_data = request.args.get('show_data') == "true"

   # You can now use that value as any other in your template.
   # Also, I would suggest renaming "data"
   # To someone who reads your code, it looks like this variable contains
   # data, when it's actually just a boolean to show/hide the data.
   return render_template('index.html', data=show_data)

你需要让你的flask服务器“监听”你的url应用页面

所以您需要导入请求

像这样:

from flask import request

现在在def index():中,您需要添加

var_name = request.args.get('var_name') = true

你的html链接

<a href="#" onClick="location="yourpage?var_bame==true">sutfile</a>

现在,当您单击链接时,新的url就是您的页面,var name=true

在flask服务器中,var=true和if条件将起作用

<label>vCenterAddress:<select> {% if data == true %} {% for a in vCenterAddress %} <option value="">{{ a[0] }}</option> {% endfor %} {% endif %}</select></label>

相关问题 更多 >