繁体   English   中英

将 python 列表传递给 jinja 模板中的 JavaScript

[英]Pass python list to JavaScript in a jinja template

我正在使用 flask 构建一个 CRUD 应用程序。 我完成了创建、读取和删除。 留下更新部分。 要更新的记录将显示在 html 表格中,以便编辑显示的数据库记录。

我的问题是当数据库记录显示在表单中时,我希望根据数据库记录中的值选中一个复选框或选择一个下拉列表项。

Is there a way to pass the result of a database query (1 record) to JavaScript as a JavaScript array, obtain the items in the JavaScript array, and use them in JavaScript statements to control check boxes?

@app.route('/update/<int:id>/')
def update(id):

    cur=mysql.connection.cursor()
    cur.execute("SELECT * FROM profiles where entity_id = %s", (id,))
    row=list(cur.fetchall())
    cur.close()
    return render_template('profile-update.html', data = row)

下面是模板

<!DOCTYPE html> 
<html>
<head>

</head>
<body class="hold-transition skin-blue layout-top-nav">

  <div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="inlineRadioOptions"             
     id="inlineRadio1" value="option1">
    <label class="form-check-label" for="inlineRadio1">company</label>
  </div>
  <div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="inlineRadioOptions"
     id="inlineRadio2" value="option2">
    <label class="form-check-label" for="inlineRadio2">partnership</label>
  </div>
  <div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="inlineRadioOptions" 
     id="inlineRadio3" value="option3"`enter code here`>
  </div>
</body>
</html>

我对此进行了广泛的研究,但建议的解决方案似乎不起作用

您使用jinja 标记传递到模板中的数据。

/templates/demo_template.html

*{{data}}*

/main.py

import flask

app = flask.Flask(__name__)

@app.route('/demo')
def demo():
    data = [dict(greeting='hello!'),dict(greeting='world!')]
    return flask.render_template('demo_template.html', data=data)

if __name__ == "__main__":
    app.run()

浏览器中的 output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM