Javascript 中的模板标记

Template Tag in Javascript

我的 Django 模板标签在我的 javascript 中不起作用。我最近的错误是:SyntaxError: expected expression, got '&' var resourceTypes = ['Structural Model', 'X-Ray Diffraction']

我怎样才能让它工作?我需要将这些 Django 变量放入 js 中,以便我可以创建图表(我正在使用 Google 图表)

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

您可以考虑使用分配标签:

from collections import Counter

@register.assignment_tag(takes_context=True)
def get_resource_types(context):
    values = dict(Counter(list(map(str, ResourceType.objects.values_list('data_type', flat=True)))))
    return {'resource_types': values}

这将为您提供值列表中每个 data_type 字符串的计数,例如:

{'data type 1': 3, 'data type 2': 10, 'data type 3': 47}

然后您可以将其传递给 .addRows() 函数:

{% get_resource_types as resource_types %}

data.addRows([
    {% for data_type, count in resource_types.items %}
    ['{{ data_type }}', {{ count }}],
    {% endfor %}
]);

这应该允许您在单个数据库查询中执行所有操作,而不是必须查询每个数据库。您还可以使用查询集上每种类型的聚合计数来做到这一点。根据我们讨论的数据量,我不能确定哪个会更快。