I am trying to pass my variable from Django's view to a javascript file. I read the stack question here (How can I pass my context variables to a javascript file in Django?) to get a few guidance but I am trying something a little bit different. I want to pass variable to the javascript file within that particular javascript reference script tag or changing the order of variable declaration. It is easier to show by example:
My somerandom.js:
console.log(variable);
What works:
{% extends base.html %}
{% load static %}
{% block body %}
<h1> Hello, World! </h1>
{% endblock body %}
{% block javascript %}
<script>
var variable = {{ my_var }};
</script>
<script src="{% static "app1/bootstrap/js/somerandom.js" %}"></script>
{% endblock javascript %}
What doesn't work:
Edit: It doesn't work because the in developer tool (press F12 in Chrome) I see this error: Uncaught ReferenceError: variable is not defined
1:
{% extends base.html %}
{% load static %}
{% block body %}
<h1> Hello, World! </h1>
{% endblock body %}
{% block javascript %}
<script src="{% static "app1/bootstrap/js/somerandom.js" %}"></script>
<script>
var variable = {{ my_var }};
</script>
{% endblock javascript %}
2:
{% extends base.html %}
{% load static %}
{% block body %}
<h1> Hello, World! </h1>
{% endblock body %}
{% block javascript %}
<script src="{% static "app1/bootstrap/js/somerandom.js" %}">
var variable = {{ my_var }};
</script>
{% endblock javascript %}
Reason I want those 2 to work is so I can organize and refer to my variables properly once my code gets longer. And in this link (http://www.mutaku.com/wp/index.php/2012/03/accessing-django-template-variables-in-javascript/), it shows that we can declare variable after referencing the javascript file.