将列表从视图上下文传递到模板,并在temp中将其指定为数组

2024-03-29 13:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从视图上下文传递一些列表:

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 }}"

但随后变量被指定为一个大字符串,并带有不需要的编码:

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

模板循环将起作用:

 {% for x in l %}
      console.log("{{x}}")
 {% endfor %}

但我不想重复。我想马上分配名单。你知道吗

有没有简单的方法?你知道吗

我是否应该使用模板循环将字符串拆分为数组项?你知道吗


Tags: 字符串testlog视图模板列表returnrequest
2条回答

发生这种情况的原因是Django模板在默认情况下将转义字符。例如,&替换为&amp;"替换为&quot;。可以使用^{} template filter [Django-doc]将内容标记为安全的。你知道吗

此外,最好使用json.dumps将数据转换为JSON blob,因此:

import json

def list_test(request):
    l = ['a', 'b', 'c']
    context = {'l': json.dumps(l)}
    return render(request, 'app/list_test.html', context)

并将其渲染为:

<script>
    let l = {{ l|safe }};
    console.log(l);
</script<

使用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 }}");

相关问题 更多 >