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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
You have to create a custom twig extension that you could use in your twig template.
You can follow the symfony documentation