I've been struggling with this too. On the surface it seems that the above solutions should work. However, the django architecture requires that each html file has its own rendered variables (that is, {{contact}}
is rendered to contact.html
, while {{posts}}
goes to e.g. index.html
and so on). On the other hand, <script>
tags appear after the {%endblock%}
in base.html
from which contact.html
and index.html
inherit. This basically means that any solution including
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
is bound to fail, because the variable and the script cannot co-exist in the same file.
The simple solution I eventually came up with, and worked for me, was to simply wrap the variable with a tag with id and later refer to it in the js file, like so:
// index.html
<div id="myvar">{{ myVar }}</div>
and then:
// somecode.js
var someVar = document.getElementById("myvar").innerHTML;
and just include <script src="static/js/somecode.js"></script>
in base.html
as usual.
Of course this is only about getting the content. Regarding security, just follow the other answers.