How to call Python variable in JavaScript?
I have a Python function that returns some value. Also I connected to my project Google Charts. So I need to pass that value to a js function in html file of Google Charts. The project is on Django btw.
What is the most correct way to do this?
{% extends "gappi_tmp/wrapper.html" %}
{% block content %}
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['lol',11], // The variable should be here, instead of '11'
['Eat', 11] // Here another variable
]);
var options = {
title: 'Inbox | Outbox'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div style="padding-top: 5px; background: cornflowerblue; width: auto; height: 300px;" id="piechart"></div>
</body>
{% endblock %}
You should render your template with a context: https://docs.djangoproject.com/en/2.0/ref/templates/api/#rendering-a-context
The method of passing the context to the template depends on how your views are written.
Function-based views
Pass the context dictionary to the render()
function:
https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#optional-arguments
from django.shortcuts import render
def my_view(request):
# View code here...
context = {'foo': 'bar'}
return render(request, 'myapp/index.html', context=context)
Class-based views
Write your own implementation of the add_context_data()
method: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#adding-extra-context
from django.views.generic import DetailView
from books.models import Book, Publisher
class PublisherDetail(DetailView):
model = Publisher
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context
Once you passed key: value
context to the template, you should use it in the template like this: {{ key }}
.
https://docs.djangoproject.com/en/2.0/topics/templates/#variables
<script type="text/javascript">
var a = "{{ key|escapejs }}";
</script>
escapejs template filter is required to prevent possible XSS vulnerabilities. If you need to pass JSON, you could check out Django ticket #17419
In case you want to access python vars in a separated js file. You can define js global vars with the value of python vars, then access those global vars in a separated js file.