Decoding Json in Twig

Decoding JSON in Twig

That's easy if you extend twig.

First, create a class that will contain the extension:

<?php

namespace Acme\DemoBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;
use \Twig_Extension;

class VarsExtension extends Twig_Extension
{
protected $container;

public function __construct(ContainerInterface $container)
{
$this->container = $container;
}

public function getName()
{
return 'some.extension';
}

public function getFilters() {
return array(
'json_decode' => new \Twig_Filter_Method($this, 'jsonDecode'),
);
}

public function jsonDecode($str) {
return json_decode($str);
}
}

Then, register that class in your Services.xml file:

<service id="some_id" class="Acme\DemoBundle\Twig\Extension\VarsExtension">
<tag name="twig.extension" />
<argument type="service" id="service_container" />
</service>

Then, use it on your twig templates:

{% set obj = form_label(category) | json_decode %}

Why isn't there a native json_decode in Twig?

json_encode makes sense, json_decode however does not really.

It adds a non trivial dependency towards the fact that the data passed is JSON.

Filters are here to transform data not crafting data. Computations (that are not transformations) should be made ahead of time.

One could also argue that json_encode should be done ahead of time but considering how frequent it is to return/send JSON it seems fair enough to do it in the template.

PS :

This seems to be a primarily opinion based question (unless there is an official answer to it).

Twig loop through JSON

You should json_decode the JSON first, before you're passing it to twig. With that, you have an array or object, that you can loop through.

$objJson = json_decode($yourDBArray['menu']);
$arrJson = json_decode($yourDBArray['menu'],true);

In the code you've provided, the JSON is a string and not an array nor an object.

Accessing a decoded json string value in twig

From the documentation here, you can pass it as an option. See the options here.

You want to pass JSON_OBJECT_AS_ARRAY

Decodes JSON objects as PHP array.

So basically you want to do:

{% set beds = specifics[website.id].0.standardBedTypes|json_decode(constant('JSON_OBJECT_AS_ARRAY'))  %}

If you want to access to objects properties, you can do it using the attribute function.

How to render json into a twig in Symfony2

I don't understand what you are trying to achieve but you can simply send json encoded and normal data to your twig, to use it how you want

return $this->render('admin/tarifas/index.html.twig', array(
'tarifas' => $tarifas
'json_tarifas' => json_encode($tarifas)
));


Related Topics



Leave a reply



Submit