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:
/**
* Return a JSON string representing this class.
*/
public function getJson()
{
return json_encode(get_object_vars($this));
}
And in the form (something like):
$builder->add('categories', 'entity', array (
...
'property' => 'json',
...
));
Afterwards, I was hoping to json_decode
it in Twig...
{% for category in form.categories %}
{# json_decode() part is imaginary #}
{% set obj = category.vars.label|json_decode() %}
{% endfor %}
json_encode()
it in PHP? – Wifelyjson_encode(get_object_vars($this))
. The problem is decoding since it has to be in Twig and not PHP. – Silverfish$builder
) queries for categories by itself and all I can do is configure which property will be used to label it in the actual form to be rendered. – Silverfishproperty
) in its form builder; which is afterall a label. However, I believe this worked (despiteform_label
supposedly being HTML) as I just did it earlier today and stumbled on decoding. I'll recheck and get back on this. Thanks! – Silverfish