I have Python code, in which I'm using jinja to send data to a template in Flask. I can access the code just find in HTML, but when I try displaying the data in Javascript, it doesn't work. For example, here's my Python code:
name = "Steve"
return render_template('simple.html',data=json.dumps(name))
And in my simple.html code, in the html body:
<script>
var name = {{ data }};
alert(name);
</script>
The error in my console says "SyntaxError: Unexpected token '&'"
I know I've seen this problem before, I'm forgetting how to solve it though.
Never mind, I got it. I needed to use safe to escape the code. Example:
<script>
var name = {{ data|safe }};
alert(name);
</script>
Flask got a builtin filter tojson. Therefore we can do:
flask:
data = {
"firstname": "Steve",
"lastname": "Jobs"
}
return render_template('simple.html', data=data)
jinja2:
<script type="text/javascript">
var data = {{ data | tojson }};
console.log(data);
</script>
Use it like this.
<script type="text/javascript">
var data = '{{ invoice.inv_num }}';
</script>
Just put quotes around it for data part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With