Until now I have been including scripts in my templates by using {% load static %} and having the javascript code in the static directory, separated from html files, because I thought it was the best practice.
But more and more I need to use context variables in the javascript. Since template tags cannot be integrated directly in the individual javascript static files (as far as I know), I have been importing these values in the javascript from the rendered template by using selectors. For example:
<!--template.html-->
<div id="url_ajax" style="display:none">{% url
"images:products" %}</div>
{%load static%}
<script src="{% static "js/ajax.js" %}"></script>
/*Ajax.js*/
url_ajax = document.getElementById("url_ajax").innerHTML
$.post(url_ajax, {
rankit: this.rankit,
pd: JSON.stringify(pd)
},
function(data) {
if (data['status'] == 'ok') {
[...]
}
}
);
Although this works, I am feeling this is not a good practice due to security reasons or scalability. But I do not know another way of integrating context variables in the javascript rather than integrating javascript code directly in the template, which is neither a good approach if that code will be used in many templates.
As a Django learner I would like to know which is the most often used approach in these situations: separated javascript files which takes context variables from the rendered template, javascript code inserted directly in the template html, or a third approach which I don´t know?