Using unquoted json formatted result set in symfony2 twig

In the request->process->response world of the MVC infrastructure, Symfony2 fits just perfect.

I was working on some data intensive site. All I want was to get the set of records from the mysql database and pass it to the front end through the controller. The front end wants the JSON format of the result set. The front end is getting the polished output of the twig

The problem
Front-end is not happy since it is getting quote-escaped version of JSON

The solution

Very very very simple. Rather than passing the json_encode(all_cars), where all_cars being the array of results coming from database or whatever it is, just pass the array it self

{{ all_cars | json_encode | raw }}

Yup, twig will not try to escape the quotes in this case since it is told to present raw.

Additional View

As you can see in this menu, both JSON and html views are together as combo. From design point of view this is not a good approach.

Better approach

You can bake the whole view right in the view and you might not want additional javascript logic on your view

OR
Have specific API to return 100% JSON response for the request like

some domain dot com/all/cars

By hitting this from, say your ajax call, you will be provided with json formatted list of all cars.

Since you are calling it from javascript, it will be directly coming to its home and no funny business would be there.
Then you will have another url call to load the page say:

some domain dot com/cars

where it will simply load the bare html format to the front-end and the front-end will know what to do with it.

Of course, this would have two trips and even more so it would be suitable for 80-90% of ajaxy sites..

EnJoY!