将Python的数组从python传递给Javascript

时间:2015-03-21 14:26:47

标签: javascript python django

我无法访问从python脚本传递到javascript的dicts数组。当我使用以下代码时,没有弹出警告消息。我在这里做错了什么?

errors = [1, 2]
graphs = [{'A': 1}, {'B': 2}]
return render(request, 'index.html', {'errors': errors, 'graphs': graphs})

# index.html
<script>
if ({{ graphs }}){
    alert('Detected');
}
if ({{ errors }}){
    alert('Detected');
}
</script>

我甚至尝试将此转换为json,但仍然存在同样的问题。

mygraphs = json.dumps(graphs)
return render(request, 'index.html', {'errors': errors, 'graphs': mygraphs})

我能够在HTML中正确访问数组。

{% for graph in graphs %}
    <li style="color: red;">Element detected</li>
{% endfor %}

两次打印Element detected。但我无法在剧本中做到这一点。

2 个答案:

答案 0 :(得分:0)

Django模板替换&#39;实体的单引号。因此,将safe过滤器添加到graphs变量:

if ({{ graphs|safe }}){
    alert('Detected');
}

答案 1 :(得分:0)

这应该有效

if("{{ graphs|safe }}"){
    alert('Detected');
}

请参阅此Django Template Variables and Javascript