This question must be obvious but I can't figure it out.
In a template, I link to a js file in my media directory. From that file, I would like to access a context variable like {{my_chart}}
.
But is the syntax different?? Thank you!!
As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script . The new tag will safely serialize template values and protects against XSS. Django docs excerpt: Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.
A context is a variable name -> variable value mapping that is passed to a template. Context processors let you specify a number of variables that get set in each context automatically – without you having to specify the variables in each render() call.
As django is a backend framework, hence to use the power of python to use that data dynamically requests need to be generated. These requests can be type GET, POST, AJAX etc. But without making any call to the backend the only way to use that data dynamically is to pass it to JavaScript.
In addition to Andrzej Bobak's answer, you can also generate a global variable in Javascript from your template. For example, your template might generate code like this:
<script> var my_chart = {{ the_chart }}; </script>
Your script could then refer to my_chart
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With