I'm building a website using the (excellent) Python Flask framework in which there is a templates/
folder and a static/
folder. As the names suggest, the templates folder contains the templates which are rendered through the jinja2 templating engine and the static folder contains static content such as css, images, and static javascript files.
The javascript files is what I'm having trouble with though. Sometimes I want to place a jinja variable in a piece of js like this for example:
var requestJson = {'text': messageText, 'toUserId': {{ user.id }}};
If I do this in a do this in a .js
file in the static/
folder though, it isn't rendered, so this only works if I place it between <script>
tags in the template file. That works, but it feels kinda messy because I now have some js in the static folder, and some js in the template files.
I could of course solve this by defining a document.toUserId = {{ user.id }};
in the template and using that in the .js files, but yeah, that also feels kinda like a hack.
So my question is; what is the best/pythonic/neatest way of handling the insertion of dynamic values from jinja in javascript?