Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Twig to generate JSON

I want to have a URL that returns a simple JSON object. I am trying to use Twig to generate the JSON object:

{
"urls": [
{% for child in page.root %}
    "{{ child.url }}"{% if not loop.last %},{% endif %}
{% endfor %}
]
}

The carriage returns will not remain in place though, and I keep getting a result that looks like this:

{'urls':['../ants/','../brick-report/','../the-pollution-intervention/','../barclay/','../broken-advertising/','../aldat-n-densom/','../thisisart/','../there-she-goes-again/']}

which Jquery will not parse with it's ajax or getJSON methods. It's totally ignoring this JSON. How might I convince Twig to put the right whitespace in place? I've looked at the manual and it only seems concerned with NOT inserting whitespace.

like image 989
russellmania Avatar asked Jan 28 '14 03:01

russellmania


4 Answers

Twig has a filter for this.

json_encode, it uses PHP json_encode function.

for your case:

{{ {'urls': page.root}|json_encode }}

will output

{"urls":["..\/ants\/","..\/brick-report\/","..\/the-pollution-intervention\/","..\/barclay\/","..\/broken-advertising\/","..\/aldat-n-densom\/","..\/thisisart\/","..\/there-she-goes-again\/"]}

the code is tested and works. For more information take a look at the Twig Documentation for json_encode.

like image 173
DasBaconfist Avatar answered Nov 05 '22 05:11

DasBaconfist


Generally it would make more sense to make controller return json directly, by returning JsonRespnse object

But if you really need to output JSON in Twig and assign it to variable, you can also use:

let foo = {{ bar|json_encode|raw }}
like image 44
KoviNET Avatar answered Nov 05 '22 05:11

KoviNET


This works for me (twig template):

var parsedJSON = JSON.parse('{{ ['one', 'two', 'three']|json_encode|e('js') }}');

And this:

console.log(parsedJSON);

outputs:

 Array ["one", "two", "three"]

in browser's console.

like image 13
biera Avatar answered Nov 05 '22 05:11

biera


Don't use Twig to generate your json response.

In your controller, use:

return new Response(json_encode($var));

Sample:

public function sampleAction()
{
    $urls = array('../test', '../something', '../sample');
    return new Response(json_encode($var));
}

If URLs are generated from Symfony2 routes, you can use:

public function sampleAction()
{
    $urls = array(
             $this->generateUrl('my_test'),
             $this->generateUrl('my_something'),
             $this->generateUrl('my_sample'),
    );
    return new Response(json_encode($var));
}
like image 3
Alain Tiemblo Avatar answered Nov 05 '22 06:11

Alain Tiemblo