How to use core php function In Symfony framework

2019-07-10 00:31发布

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?

标签: symfony twig
2条回答
放我归山
2楼-- · 2019-07-10 01:08

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.

查看更多
别忘想泡老子
3楼-- · 2019-07-10 01:17

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

You can follow the symfony documentation

查看更多
登录 后发表回答