如何在 Dygraph 的 Django 模板中将 python 变量传递给 javascript

How to pass python variable to javascript in django template for Dygraph

我想将 Django Views.py 中的 pandas 数据帧输出发送到模板,以便在 Dygraph 中绘制图形。

如果我使用 Dygraph 脚本将数组定义保留在模板中,Dygraph 将会显示。如果我将相同的数组定义复制到 views.py 并将其呈现给模板,则图形将不会显示。

来自 Dygraphs 的示例数组 (http://dygraphs.com/data.html#array)。它工作正常。 output.html:

<div id="graphdiv"></div>

<script>
new Dygraph(
document.getElementById("graphdiv"),

[
              [1,10,100],
              [2,20,80],
              [3,50,60],
              [4,70,80]
            ]
,
);
</script>

下面是我对 views.py 中定义的数组的意图,但这不会呈现图形。

Views.py:

def output(request): 

    DAT =   [
                [1,10,100],
                [2,20,80],
                [3,50,60],
                [4,70,80]
              ]

    #DAT = json.dumps(DAT) This doesn't seem to help either.

    data = {
     'DAT': DAT,
    }
    return render(request, 'cylon/output.html', data)
 ------------------------------------------------------
Output.html:

<div id="graphdiv"></div>

<script>
new Dygraph(
document.getElementById("graphdiv"),

"{{DAT}}"
,
);
</script>

我认为你需要传递 json 数据并在解码之后。

Python

import json

def output(request): 
    DAT = [
        [1,10,100],
        [2,20,80],
        [3,50,60],
        [4,70,80]
    ]

    data = {
     'DAT': json.dumps(DAT),
    }
    return render(request, 'cylon/output.html', data)

HTML

<script>
  var coordinates = JSON.parse('{{ DAT }}');
  new Dygraph(document.getElementById("graphdiv"), coordinates);
</script>