2

I am new with Symfony and I've searched a lot on the net how to use core PHP functions like array functions (in_array , array_combine) , string functions (strpos , strlen) , date functions (date,timestamp),etc.. In Symfony Twig file?

2 Answers 2

2

Firstly, create Twig/Extension directory into your bundle. Sample: AppBundle/Twig/Extension

Then, create a class for your function name. I create a JsonDecode and i use every twig file this function;

namespace AppBundle\Twig\Extension;

class JsonDecode extends \Twig_Extension {
    public function getName() {
        return 'twig.json_decode';
    }
    public function getFilters() {
        return array(
            'json_decode' => new \Twig_Filter_Method($this, 'jsonDecode')
        );
    }
    public function jsonDecode($string) {
        return json_decode($string);
    }
}

Then,

add lines into services.yml;

twig.json_decode:
    class: AppBundle\Twig\Extension\JsonDecode
    tags:
        - { twig.extension }

that's enough.

Sign up to request clarification or add additional context in comments.

16 Comments

Thanks For Help me , I have one query Which Extension i set on JsonDecode file (php , twig , or other) ?
so you will create php file undet Twig/Extension what you want function, you will set name it.
ok, But how to Use That function on twig file because right now it give me below error: Code: {{jsonDecode(result.id)}} Error: Unknown "jsonDecode" function.
I also try below Code in Twig File and that give me error. code: {{result.id|jsonDecode(result.id)}} Error: Unknown "json_decode" filter. Did you mean "json_encode"?
{{ result | json_decode () }} or {{ json_decode(result) }} one of them
|
1

You have to create a custom twig extension that you could use in your twig template.

You can follow the symfony documentation

1 Comment

Thanks for help use, now problem is filter not found by symphony so for that how to register custom extension class as a service , Please replay me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.