Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jinja to send data to Javascript

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.

like image 915
Amanda_Panda Avatar asked Nov 23 '14 22:11

Amanda_Panda


3 Answers

Never mind, I got it. I needed to use safe to escape the code. Example:

<script>
var name = {{ data|safe }};
alert(name);
</script>
like image 78
Amanda_Panda Avatar answered Nov 20 '22 21:11

Amanda_Panda


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>
like image 43
aGuegu Avatar answered Nov 20 '22 19:11

aGuegu


Use it like this.

<script type="text/javascript">
    var data = '{{ invoice.inv_num }}';
</script>

Just put quotes around it for data part.

like image 24
ChandyShot Avatar answered Nov 20 '22 19:11

ChandyShot