How to use core php function In Symfony framework Twig file

安稳与你 提交于 2020-01-24 15:51:45

问题


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



来源:https://stackoverflow.com/questions/47011566/how-to-use-core-php-function-in-symfony-framework-twig-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!