【问题标题】:How to call Python variable in JavaScript?如何在 JavaScript 中调用 Python 变量?
【发布时间】:2018-10-23 00:11:31
【问题描述】:

我有一个返回一些值的 Python 函数。我还连接到我的项目 Google Charts。所以我需要将该值传递给 Google Charts 的 html 文件中的 js 函数。顺便说一句,该项目在 Django 上。

最正确的方法是什么?

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

【问题讨论】:

    标签: javascript python html json django


    【解决方案1】:

    您应该使用 context 呈现您的模板: https://docs.djangoproject.com/en/2.0/ref/templates/api/#rendering-a-context

    将上下文传递给模板的方法取决于您的视图是如何编写的。

    基于功能的视图

    context 字典传递给 render() 函数: 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)
    

    基于类的视图

    编写您自己的add_context_data() 方法实现: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
    

    key: value 上下文传递给模板后,您应该像这样在模板中使用它:{{ key }}https://docs.djangoproject.com/en/2.0/topics/templates/#variables

    <script type="text/javascript"> 
       var a = "{{ key|escapejs }}";
    </script>
    

    escapejs 模板过滤器是防止可能的 XSS 漏洞所必需的。如果需要传递 JSON,可以查看 Django 票证#17419

    【讨论】:

      【解决方案2】:

      如果您想在单独的 js 文件中访问 python 变量。您可以使用 python vars 的值定义 js 全局变量,然后在单独的 js 文件中访问这些全局变量。

      【讨论】:

        【解决方案3】:

        在 Django 中动态生成上述页面,包括来自您的 python 代码的必要 json 数据对象

        来自here

        【讨论】:

          【解决方案4】:

          如果您的 html 文件中有 js 文件,并且不在单独的 js 文件中,因为通过上下文传递的变量在渲染中可用模板,您可以这样进行。

          通过上下文将所有变量发送到模板之后。

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

          你也可以循环播放。

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

          基本上,你必须知道你可以使用它,这取决于你真正想做什么。

          【讨论】:

            猜你喜欢
            • 2017-03-20
            • 2015-04-19
            • 2020-08-03
            • 2014-06-30
            • 1970-01-01
            • 1970-01-01
            • 2015-06-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多