Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't use inner functions with Twig_SimpleFilter in Twig_Extension class

Tags:

php

twig

symfony

I have a twig based project with Symfony 2. Due to Symfony 2 nature, Namespaces are used. Because of this i am unable to provide global functions outside of namespace.

This is my Twig Extension class:

<?php
namespace Web\MailBundle\Twig;

use Twig_Extension, Twig_SimpleFilter;

class Twig extends Twig_Extension
{
    public function getName()
    {
        return 'twig_extension';
    }

    public function getFilters() {
        return array(
            'shortKey'  => new Twig_SimpleFilter('shortKey', 'myCustomFilterFunction')
        );
    }

    public function myCustomFilterFunction() {
        //code here...
    }

Result: FatalErrorException: Error: Call to undefined function myCustomFilterFunction()

Why: Because, Twig is trying to find this function but it is inside of a class. If i move it to outside of class this time i face with namespaces. Because it is namespaced.

Research: I digg the codes. Twig do the same thing. They write the filters and functions outside of class. But due to namespace i canno do that. If possible i wanto to do that by using proper solution. If it fails; I will came with the latest solution which is creating another php file without namespace and include it to the project...

--

How can i get over it? Twig Filter has been deprecated and we have to use SimpleFilter method. But i just couldn't get it done.

like image 218
xangr Avatar asked Feb 04 '13 12:02

xangr


1 Answers

You can pass a array-based callable as the second parameter to the Twig_SimpleFilter constructor - in your case, use an array like so:

public function getFilters() {
    return array(
        'shortKey'  => new Twig_SimpleFilter('shortKey', array($this, 'myCustomFilterFunction'))
    );
}

which will use your object's method when the filter is used.

See the examples in the Twig documentation.

like image 100
richsage Avatar answered Sep 28 '22 01:09

richsage