我正在尝试从 View 上下文传递一些列表:
def list_test(request):
l = ['a', 'b', 'c']
context = {'l': l}
return render(request, 'app/list_test.html', context)
作为JS数组发送到前端:
<script>
let l = {{ l }}
console.log(l)
</script>
然而,这会记录
Uncaught SyntaxError: Unexpected token &
在控制台中。
我尝试将变量放在双引号中:
let l = "{{ l }}"
但是随后变量被分配为一个大字符串并使用不需要的编码:
['a', 'b', 'c']
模板循环将起作用:
{% for x in l %}
console.log("{{x}}")
{% endfor %}
但我不想迭代。我想立即分配列表。
有没有简单的方法可以做到这一点?
我应该以某种方式使用模板循环将字符串拆分为数组项吗?
最佳答案
使用 JSON:
def list_test(request):
l = ['a', 'b', 'c']
context = {'l': json.dumps(l)}
return render(request, 'app/list_test.html', context)
并在模板中将值标记为安全并解析它:
let l = JSON.parse("{{ l|safe }}");
关于javascript - 将列表从 View 上下文传递到模板并将其分配为模板中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610671/