I know how to pass a variable from Flask (python) to my template html file with {{data}}
. However I am having trouble accessing each dictionary element and its respective key-value pairs in the list in javascript.
start.py
def func1():
data = filter() #returns a list of dictionaries
return render_template("template1.html", data=data)
template1.html
<html>
<head>
.....
</head>
<body>
<p>This is html: {{data}}</p>
<script type="text/javascript" src="{{url_for('static', filename='js/add.js') }}"></script>
<script type="text/javascript">
myvar = '{{data}}';
document.write(myvar);
</script>
</body>
</html>
add.js
//code to be written here
myvar
and This is html:
both outputs out the entire list of dictionaries. I've already tried myvar[0]
but that just outputs [
for some reason. I have also done:
myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);
but that outputs [object Object]
.
I know how to pass a variable from Flask (python) to my template html file with {{data}}
. However I am having trouble accessing each dictionary element and its respective key-value pairs in the list in javascript.
start.py
def func1():
data = filter() #returns a list of dictionaries
return render_template("template1.html", data=data)
template1.html
<html>
<head>
.....
</head>
<body>
<p>This is html: {{data}}</p>
<script type="text/javascript" src="{{url_for('static', filename='js/add.js') }}"></script>
<script type="text/javascript">
myvar = '{{data}}';
document.write(myvar);
</script>
</body>
</html>
add.js
//code to be written here
myvar
and This is html:
both outputs out the entire list of dictionaries. I've already tried myvar[0]
but that just outputs [
for some reason. I have also done:
myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);
but that outputs [object Object]
.
2 Answers
Reset to default 14By placing data
in single quotes you are creating a string. To get python data types into JavaScript, serialize them with {{ data | tojson }}
.
var parsed = JSON.parse('{{data | tojson}}');
You may need to escape the output with safe
filter. See more at sending data as JSON object from Python to Javascript with Jinja
Got it!
myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);
Outputs the [object Object]
which is the dictionary at the position. So then all you need to do is document.write(parsed[0].name);
to access its name
value!