简体   繁体   中英

Pass python list to JavaScript in a jinja template

I'm building a CRUD app using flask. 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.

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?

@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 .

/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()

the output in browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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