user8163099
user8163099

Reputation:

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 %}

Upvotes: 2

Views: 13389

Answers (4)

nhd79
nhd79

Reputation: 11

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.

Upvotes: 1

d2718nis
d2718nis

Reputation: 1269

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

Upvotes: 3

Lemayzeur
Lemayzeur

Reputation: 8525

In case that you have you js file inside your html file, and not in a seperated js file, since variables passed through context are available in the rendering templates, you can proceed that way.

After sending all the variables via context to template.

var jsVariable = '{{django_value}}';

var data = google.visualization.arrayToDataTable([
    ['Task', '{{ task_variable }}'], // as string
    ['lol',{{lol_variable}}], // as integer
    ['Eat',   {{eat_variable}} ]
]);

You can also loop through.

var data = google.visualization.arrayToDataTable([
    {% for item in queryset %} // {% for item in json_response %}
        ['Task', '{{ task.attribute }}'],
    {% endfor %}  // {% endfor %}
]);

Basically, you must know that you can use it, it depends of what you really want to do.

Upvotes: 0

fistynuts
fistynuts

Reputation: 386

Generate the above page dynamically in Django including the necessary json data object from your python code

from here

Upvotes: 0

Related Questions