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 wou开发者_如何学Cld 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.
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
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;
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&param2=abc"></script>
Within your external js you can easily write a method to parse these params.
精彩评论