symfony注册Twig模板中使用自定义PHP方法

// 注:只是在此做下记录,有兴趣的可以参考,不做实际教程文档// 官方文档,https://symfony.com/doc/2.8/templating/twig_extension.html// src/AppBundle/Templating/TwigExtension/WebTwigExtension.php

<?phpnamespace AppBundle\Templating\TwigExtension;use Wiz\AdminTools\Component\Templating\CommonTwigExtension;/** * Class WebTwigExtension * @package Okura\WebBundle\Templating\TwigExtension */class WebTwigExtension extends CommonTwigExtension{    /**     * @return array     */    public function getFunctions()    {        return array(            new \Twig_SimpleFunction('web_get_MD5', array($this, 'getMD5')),        );    }    /**     * @param $str     * @return string     */    public function getMD5($str)    {        return md5($str);    }}?>// 注册服务// src/AppBundle/Resources/config/services.yml

services:    web.twig_extension.web:        class: AppBundle\Templating\TwigExtension\WebTwigExtension        arguments: [ "@service_container" ]        tags:            - { name: twig.extension }// 在twig模板中使用自定义方法

{{ web_get_MD5('test') }}// 最终页面打印出 'test' md5加密后的结果098f6bcd4621d373cade4e832627b4f6

评论

暂无评论