admin管理员组

文章数量:1356836

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=".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 %}

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./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 %}
Share Improve this question edited Feb 10, 2019 at 4:37 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked May 12, 2018 at 23:49 user8163099user8163099
Add a ment  | 

4 Answers 4

Reset to default 3

You should render your template with a context: https://docs.djangoproject./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./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./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./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.

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

from here

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.

本文标签: How to call Python variable in JavaScriptStack Overflow