Home >Backend Development >PHP Tutorial >How Can I Decode JSON in Twig Templates?

How Can I Decode JSON in Twig Templates?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 14:30:03354browse

How Can I Decode JSON in Twig Templates?

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!

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