Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass my context variables to a javascript file in Django?

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!!

like image 285
user963936 Avatar asked Dec 30 '11 20:12

user963936


People also ask

Can I use Django template variable in JavaScript?

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.

What is context variable in Django?

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.

How does JavaScript work in Django?

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.


1 Answers

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.

like image 104
Brian Neal Avatar answered Oct 03 '22 05:10

Brian Neal