Best way to get template variables from external js file

This is what I am doing now to transfer the django template variable to the JS variable:

<input type="hidden" id="django_var" value="{{variable}}" />
...
var unique_var = $('#django_var').val();

Is there an easier way to do this in a template that works outside of forms as well? Thank.

Update : the js variable will be an external file in the template, and therefore will not be able to directly call django template templates.

+5
source share
3 answers

In the header of the HTML template:

<script>
var my_var = "{{ django_var }}";
</script>
<script type="text/javascript" src="/js/my_script.js"></script>

It is important to note that you define your JS variables in the head before including your javascript file.

Then in your javascript you can access $ my_var

+17
source

- Javascript:

<script>
var MyGlobal = {
  var_1: {{var_1}},
  var_2: {{var_2}},
};
</script>

JS :

var unique_var = MyGlobal.var_2;
+15

Sometimes its cleaner does not create a whole bunch of global vars, you can pass them as parameters to the js file as follows:

<script type="text/javascript" src="/js/my_script.js?param1=xyz&amp;param2=abc"></script>

In your external js, you can easily write a method to analyze these parameters.

+1
source

All Articles