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

How Can I Decode JSON in Twig Templates?

Mary-Kate Olsen
Release: 2024-11-11 14:30:03
Original
342 people have browsed it

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);
    }
}
Copy after login

Registering the Extension:

In your Services.xml file, register the extension:

<service>
Copy after login

Using the Extension in Twig:

To use the extension in your Twig templates:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template