Issue
I am using python flask temple to build a site. I have a case where I want to send a python list to a java script. The python list contains three objects however when I do list1.length in the java script environment I see the length of this list is 23. This is most likely because java script is identifying it as a string. My question is how to make the python list stay a list once it's passed into javascript ?
# my route with python list1
@app.route('/chart_sandbox')
def chart_sandbox():
list1 = ['abc', 'def', 'hij']
return render_template("chart_sandbox.html", list1=json.dumps(list1))
# My Java script
<script type="text/javascript">
var list1 = '{{list1|tojson}}'
var listLength = list1.length
document.write(listLength)
document.write(list1)
</script>
# this is what is returned to me. As you can see java script length is seen
#as 23 instead of 3
23"["abc", "def", "hij"]"
Solution
Remove the quotes around the jinja text. That's converting your list into a string-representation of a list. Something like this should work:
var list1 = {{ list1 | tojson }};
Answered By - dizzyf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.