如何在Symfony框架Twig文件中使用核心php函数 [英] How to use core php function In Symfony framework Twig file

查看:28
本文介绍了如何在Symfony框架Twig文件中使用核心php函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Symfony 的新手,我在网上搜索了很多如何使用核心 PHP 函数,如数组函数(in_array 、array_combine)、字符串函数(strpos、strlen)、日期函数(日期、时间戳)等.. 在 Symfony Twig 文件中?

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?

推荐答案

首先,在你的 bundle 中创建 Twig/Extension 目录.示例:AppBundle/Twig/Extension

Firstly, create Twig/Extension directory into your bundle. Sample: AppBundle/Twig/Extension

然后,为您的函数名称创建一个类.我创建了一个 JsonDecode 并且我使用这个函数的每个树枝文件;

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);
    }
}

那么,

添加行到services.yml;

twig.json_decode:
    class: AppBundle\Twig\Extension\JsonDecode
    tags:
        - { twig.extension }

够了.

这篇关于如何在Symfony框架Twig文件中使用核心php函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆