Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register twig filter into Symfony 4?

I have a problem of registration with my custom twig extension in Symfony 4 . I have create extension who help me to decode my json data but it's not work. This message is display when I want to use my json_decode filter. Error message

The code of my custom twig filter :

<?php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getName() {
        return 'Json Decode';
    }

    public function getFunctions()
    {
        return [
            new TwigFilter('json_decode', [$this, 'json_decode']),
        ];
    }

    public function json_decode($input, $assoc = false) {
       return json_decode($input,$assoc);
    }
}
?>

Here is a twig_exension.yaml

services:
    _defaults:
        public: false
        autowire: true
        autoconfigure: true

    # Uncomment any lines below to activate that Twig extension
    #Twig\Extensions\ArrayExtension: null
    #Twig\Extensions\DateExtension: null
    Twig\Extensions\IntlExtension: null
    Twig\Extensions\TextExtension: null
    App\Twig\AppExtension: null

Here is the line that return and error in my twig file

{% set commande = render(controller('App\\Controller\\StoreController::getProduitsCommandes')) | json_decode  %}

Here is the Response return in StoreController.php

$response = new Response(json_encode(["produits"=>$produitsArray,"total_ht"=>$total_ht,"tva"=>$tva,"nbre_produits"=>$nbre_produits]));
$response->headers->set('Content-Type', 'application/json');
return $response;

When I type php bin/console debug:twig --filter=json_decode The debugger return me this result

---------

* json_decode(input, assoc = false)

Thank you for your attention If any people has a solution it will help me

like image 210
Alladin Avaïka Avatar asked Feb 01 '26 18:02

Alladin Avaïka


1 Answers

As the errors states the filter can not be found. This is due to the fact you are trying to register your filter as a function, move the registration to the getFilters method instead. Also it's perfectly viable to chain existing functions

<?php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [
            new TwigFilter('json_decode', 'json_decode'), //just chain to existing PHP function
        ];
    }
}

sidenote The method getName is now obsolete and can be removed as it has been deprecated and isn't used anymore in the code

source

like image 104
DarkBee Avatar answered Feb 03 '26 08:02

DarkBee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!