Skip to content

Instantly share code, notes, and snippets.

@mylk
Last active August 14, 2016 14:19
Show Gist options
  • Save mylk/7f41de5f38577b44e2a5c953e9f72364 to your computer and use it in GitHub Desktop.
Save mylk/7f41de5f38577b44e2a5c953e9f72364 to your computer and use it in GitHub Desktop.
Twig filter that converts a JSON string to object
<?php
/*
* Installation:
* =============
* # services.yml
* services:
* # ...
* acme.twig.json_decode:
* class: Acme\AcmeBundle\Twig\JsonDecodeExtension
* tags:
* - { name: twig.extension }
* Usage:
* ======
* {% set customerProperties = entity.properties | jsonDecode %}
*
* {{ customerProperties.firstName }}
*/
namespace Acme\AcmeBundle\Twig;
class JsonDecodeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
"jsonDecode" => new \Twig_Filter_Method($this, "jsonDecode")
);
}
public function jsonDecode($string)
{
return \json_decode($string);
}
public function getName()
{
return "jsonDecode.extension";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment