【发布时间】:2019-02-25 08:40:50
【问题描述】:
当我尝试将 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>
【问题讨论】:
-
{{labels | safe}}docs -
传奇。谢谢@K
-
确实是传奇。检查了这些负载。这是唯一可以将简单的 Python 列表放入我的 Javascript 的方法
标签: javascript python django python-3.x django-2.0