Decoding JSON in Twig
Decoding JSON in Twig templates is possible through a custom extension. Here's how:
Creating the Extension:
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); } }
Registering the Extension:
In your Services.xml file, register the extension:
<service>
Using the Extension in Twig:
To use the extension in your Twig templates:
{% set obj = form_label(category) | json_decode %}
The above is the detailed content of How Can I Decode JSON in Twig Templates?. For more information, please follow other related articles on the PHP Chinese website!