2016-06-19 35 views
1

我試圖使用google charts來顯示一些數據。如文檔所描述的,我把這個代碼我templatedjango變量爲javascript

<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 tmp = document.getElementById('result').value; 
    var data = google.visualization.arrayToDataTable([ 
     ['Year', 'Sales', 'Expenses'], 
     ['2004', 1000,  400], 
     ['2005', 1170,  460], 
     ['2006', 660,  1120], 
     ['2007', 1030,  540]] 
    ); 

    var options = { 
     title: 'Company Performance', 
     curveType: 'function', 
     legend: { position: 'bottom' } 
    }; 

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); 

    chart.draw(data, options); 
    } 
</script> 
<div id="curve_chart" style="width: 900px; height: 500px"></div> 

,它工作正常。但我需要通過一些自定義數據,所以我也:

views.py

def home(request): 
    example = [ 
     ['Year', 'Sales', 'Expenses'], 
     ['2004', 1000,  400], 
     ['2005', 1170,  460], 
     ['2006', 660,  1120], 
     ['2007', 1030,  540] 
    ] 
    return render(request, 'home.html', {'example': example}) 

如實例i的數據所使用的相同的數組。接下來,我取代了JavaScript代碼陣列{{ example }}

var data = google.visualization.arrayToDataTable({{example}}); 

並沒有任何反應。 Google圖表不再繪製在我的網頁上。
什麼即時做錯了?此外,我試圖在Python代碼中使用json.dumps,它並沒有爲我工作。

回答

1

您應該簡單地把你的名單列表變爲有效的JSON你將它傳遞給模板之前:

import json 

def home(request): 
    example = [ 
     ['Year', 'Sales', 'Expenses'], 
     ['2004', 1000,  400], 
     ['2005', 1170,  460], 
     ['2006', 660,  1120], 
     ['2007', 1030,  540] 
    ] 
    example = json.dumps(example) 
    return render(request, 'home.html', {'example': example}) 

確保您使用的safe模板標籤:

var data = google.visualization.arrayToDataTable({{example|safe}}); 

是什麼當你嘗試這樣的錯誤時,你會得到什麼錯誤?

+0

好吧,我也試過了,試圖在'javascript'中使用'JSON.parse()'方法,但沒有任何結果。那麼,關鍵是過濾器'安全'這就是答案,謝謝! – Mental