0

I am not able to access an array of dicts passed from python script to javascript. When I use the following code, there is no alert message popping up. What am I doing wrong here?

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>

I even tried converting this to json, but still same problem.

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

I am able to access the array fine inside the HTML.

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

prints out Element detected twice. But I am not able to do this inside the script.

user828647
  • 505
  • 1
  • 10
  • 27

2 Answers2

0

Django template replaces single quotes by &#39; entity. So add the safe filter to the graphs variable:

if ({{ graphs|safe }}){
    alert('Detected');
}
catavaran
  • 44,703
  • 8
  • 98
  • 85
0

This should work

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

Refer this Django Template Variables and Javascript

Community
  • 1
  • 1
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • Sorry, did not work. Also see my edit, I don't think `safe` has anything to do with it, even a simple array `errors` is not detected. – user828647 Mar 21 '15 at 14:54
  • "safe" is for convert `'` to back only. I just tested here.Did you try without `json.dumps` – itzMEonTV Mar 21 '15 at 14:56