Skip to content
Advertisement

Decoding JSON in Twig

Is is possible to decode JSON in twig? Googling doesn’t seem to yield anything about this. Does decoding JSON in Twig not make sense?


I’m trying to access 2 entity properties on an Symfony2’s entity field type (Entity Field Type).

After coming across 2 previous SO questions ( Symfony2 entity field type alternatives to “property” or “__toString()”? and Symfony 2 Create a entity form field with 2 properties ) which suggested adding an extra method to an entity to retrieve a customized string rather than an entity attribute, I thought of (and did) returning a JSON string representing an object instance.

Somewhere in the entity class:

JavaScript

And in the form (something like):

JavaScript

Afterwards, I was hoping to json_decode it in Twig…

JavaScript

Advertisement

Answer

That’s easy if you extend twig.

First, create a class that will contain the extension:

JavaScript

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

JavaScript

Then, use it on your twig templates:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement