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
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.
16 Comments
Sandeep Gajera
Thanks For Help me , I have one query Which Extension i set on JsonDecode file (php , twig , or other) ?
Mert Simsek
so you will create php file undet Twig/Extension what you want function, you will set name it.
Sandeep Gajera
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.
Sandeep Gajera
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"?
Mert Simsek
{{ result | json_decode () }} or {{ json_decode(result) }} one of them
|
You have to create a custom twig extension that you could use in your twig template.
You can follow the symfony documentation
1 Comment
Sandeep Gajera
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?