Paulo Borralho Martins Paulo Borralho Martins - 3 months ago 12
Twig Question

JSON encode in Slim framework

I am having problems sending a JSON encoded array to my view.

So I am doing this in my route

$data['values'] = array('name'=>'John');
$data['values'] = json_encode($data['values']);
return $this->view->render($res, 'githubpresentation.html', $data);


And in my view, in the script tag I do this

var values = "{{values}}" ;
console.log(values);

values = JSON.parse(values);
console.log(values);


The first console.log, before the JSON.parse outputs this:

{"name":"John"}


And when I do the JSON.parse I get an error, of course

Unexpected token & in JSON at position 1


Now I could do some sort of replace of the &quot, but do I really need to? Shouldn't I be able to send a JSON from the server?

Answer

This is related to the default escaping strategy. You can fix it by using the js one:

var values = "{{values|e('js')}}" ;
console.log(values);

values = JSON.parse(values);
console.log(values);

Output:

{"name":"John"}
Object {name: "John"}
Comments