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