Home  >  Article  >  Backend Development  >  How to Decode JSON in Twig?

How to Decode JSON in Twig?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 10:54:02880browse

How to Decode JSON in Twig?

Decoding JSON in Twig

Decoding JSON in Twig is possible with the help of custom Twig extensions. Here's how you can do it:

Step 1: Create the Extension Class

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);
    }
}

Step 2: Register the Extension

Add this to your Services.xml file:

<service>

Step 3: Use the Extension

In your Twig template, you can use the | json_decode filter like this:

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

This will decode the JSON string in the form_label(category) variable and assign the decoded object to obj.

The above is the detailed content of How to Decode JSON in Twig?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn