I want a complex 2d list to be brought from python to javascript. Javascript handles the numbers and list syntax (brackets and commas) just fine, but it can't understand the quotes around a string. I have tried embedding the list directly to the code and converting it to json first, but neither works. I think problem is in that javascript somehow converts "
to something else, I show what I mean in a minute.
But here's a sample code to reproduce the problem.
Action:
def problem():
this_works = [[1,2,5,6.99],[24,55,6.8,124]]
this_does_not = [["a",5,6,7],["b",8,9,10]]
return dict(locals())
View:
{{extend 'layout.html'}}
{{from gluon.serializers import json}}
<p id="test_1">unchanged</p>
<p id="test_2">unchanged</p>
<p id="test_3">unchanged</p>
<script>
var x;
x = {{=this_works}};
document.getElementById("test_1").innerHTML = x;
var y;
//y = {{=this_does_not}};
document.getElementById("test_2").innerHTML = y;
var z;
//z = {{=json(this_does_not)}};
document.getElementById("test_3").innerHTML = z;
</script>
If either of those two lines are uncommented, the code breaks. If you check the source code of the html, you can see that web2py changes "
to something else:
<script>
var x;
x = [[1, 2, 5, 6.99], [24, 55, 6.8, 124]];
document.getElementById("test_1").innerHTML = x;
var y;
//y = [['a', 5, 6, 7], ['b', 8, 9, 10]];
document.getElementById("test_2").innerHTML = y;
var z;
//z = [["a", 5, 6, 7], ["b", 8, 9, 10]];
document.getElementById("test_3").innerHTML = z;
</script>
For security reasons, the web2py template engine escapes all text inserted in the template. To prevent this, you should use the XML()
helper:
y = {{=XML(this_does_not)}};