简体   繁体   中英

How can I pass a jinja2 object to a jquery function as parameter?

In my python script, I have something like this

students = getStudent()  
return render_template('index.html', students = students)

students is a list of student, and each student has attributes like name, id, gpa, ....

In index.html, I have a selection like this

 <select class="form-control" onchange="changeStudent">
     {% for student in students %}
         <option>{{student.name}}</option>
     {% endfor %}
 </select>

Now I want to implement a jquery function that can do can for example print out the student information if that student is selected.

function changeStudent(student) {
    alert(student.name)
}

How can I do that? Thanks in advance.

If you're using an inline <script type="application/javascript"> element in your HTML you can just drop it straight in there.

Just make sure the object in your context is a JSON formatted string and that the data is genuinely safe .

view.py

import json
def index_view():
    students = json.dumps(getStudent())
    return render_template('index.html', students = students)

index.html

<html>
<body>
    <script type="application/javascript">
      var students = {{ students|safe }};
      // do your thang...    
    </script>
</body>
</html>

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