简体   繁体   English

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

[英]How to pass python variable to javascript in django template for Dygraph

I want to send a pandas dataframe output that is in Django Views.py, to the template in order to graph in a Dygraph. 我想将Django Views.py中的pandas数据框输出发送到模板,以便在Dygraph中绘图。

The Dygraph will display if I leave the array definition in the template with the Dygraph script. 如果我使用Dygraph脚本将数组定义保留在模板中,则将显示Dygraph。 If I copy that same array definition to views.py and render it to the template the graph won't display. 如果我将相同的数组定义复制到views.py并将其渲染到模板,则该图形将不会显示。

The example array from Dygraphs ( http://dygraphs.com/data.html#array ). Dygraphs( http://dygraphs.com/data.html#array )中的示例数组。 And it works correctly. 而且它可以正常工作。 output.html: 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>

Below is my intent with the array defined in views.py, but this won't render the graph. 下面是我对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>

I think you need to pass json data and after decode it. 我认为您需要传递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 的HTML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM