当我尝试将python列表传递给模板中的JavaScript时,它没有按预期将列表解析为JS数组,而是返回了此["Groceries", "Clothing", "Takeaways", "Alcohol"]
导致页面中断。
view.py
def labels():
category_labels = []
for item in Purchase.objects.order_by().values_list('type', flat=True).distinct():
category_labels.append(item)
return category_labels
def index(request):
try:
purchases = Purchase.objects.all().order_by('-time')
total_spending = round(Purchase.objects.aggregate(Sum('amount'))['amount__sum'], 2)
except Purchase.DoesNotExist:
raise Http404("Could not find any purchases.")
context = {
'purchases': purchases,
'total_spending': total_spending,
'spending_by_category': prepare_total_spending(),
'total_spending_all_categories': total_spending_all_categories(),
'labels': json.dumps(labels()),
}
return render(request, 'main/index.html', context)
index.html
<script type="text/javascript">
console.log(JSON.parse("{{labels}}"))
# => converts this to console.log(["Groceries", "Clothing", "Takeaways", "Alcohol"]) in JS and breaks.
</script>
答案 0 :(得分:0)
{{labels | safe}}
由@Klaus D解决。