0
我的Django模板標籤在我的javascript中不起作用。我最近的錯誤是:SyntaxError: expected expression, got '&' var resourceTypes = ['Structural Model', 'X-Ray Diffraction']
Javascript中的模板標籤
我該如何得到這個工作?我需要得到這些變量的Django在js中,這樣我可以創建一個圖表(我使用谷歌圖表)
的index.html
<script>
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string');
data.addColumn('number');
var resourceTypes = {{ "all"|resource_types }}
{% for x in resourceTypes %}
data.addRows([
[x, {{ x|resourceType_count }}],
]);
{% endfor %}
// Set chart options
var options = {'title':'Datasets by Type',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
templatetags.py
@register.filter(name='resource_types')
def resource_types(data_type):
resourceTypes = [ str(x.data_type) for x in ResourceType.objects.all() ]
return resourceTypes
@register.filter(name='resourceType_count')
def resourceType_count(data_type):
count = Dataset.objects.filter(data_type=ResourceType.objects.get(data_type=data_type)).count()
return count
靠得更近!謝謝@brandon解決了這個問題,但現在'{%for x in resourceTypes%}'不工作 - 任何想法爲什麼這個循環沒有去? – plact
你是什麼意思「不工作」?有錯誤嗎?循環是不是迭代?請解釋 – Brandon
沒有錯誤 - 它根本沒有迭代。我在for循環中添加了一個'console.log(x);',它甚至從不打印 – plact