简体   繁体   English

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

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

I'm building a CRUD app using flask.我正在使用 flask 构建一个 CRUD 应用程序。 I'm done with the create, read and delete.我完成了创建、读取和删除。 left with update part.留下更新部分。 The record to be updated will be shown in an html form to enable editing of the shown database record.要更新的记录将显示在 html 表格中,以便编辑显示的数据库记录。

My problem is when the database record is shown in the form, i want a checkbox to be checked or a drop down list item to be selected depending on a value in the database record.我的问题是当数据库记录显示在表单中时,我希望根据数据库记录中的值选中一个复选框或选择一个下拉列表项。

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

below is the template下面是模板

<!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>

i have research extensively on this but the suggested solutions do not seem to work我对此进行了广泛的研究,但建议的解决方案似乎不起作用

You use the data passed into your template using jinja markup .您使用jinja 标记传递到模板中的数据。

/templates/demo_template.html /templates/demo_template.html

*{{data}}*

/main.py /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()

the output in browser浏览器中的 output

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

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