Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get template variables from an external js file

This is what I am currently doing to transfer a django template variable to a JS variable:

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

Is there a more straightforward way to do this in the template, something that would work outside of forms as well? Thank you.

Update: the js variable will be an external file to the template, and thus won't be able to directly call the django template vars.

like image 950
David542 Avatar asked Sep 06 '11 00:09

David542


3 Answers

In your HTML template header:

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

The important thing to note is that you define your JS variables in the head before you include your javascript file.

Then in your javascript you can access $my_var

like image 200
Elver Loho Avatar answered Nov 15 '22 08:11

Elver Loho


Instead of adding hidden meta fields in the template, you add a little bit of inline Javascript in the template:

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

Later, in an external JS file, you can do:

var unique_var = MyGlobal.var_2;
like image 43
scribu Avatar answered Nov 15 '22 07:11

scribu


Sometimes its cleaner to not create a whole bunch of global vars, you can pass them as params to the js file like so:

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

Within your external js you can easily write a method to parse these params.

like image 25
minaz Avatar answered Nov 15 '22 09:11

minaz