user2576422
user2576422

Reputation: 93

Twig Extension Error, Symfony2

I have problem with Twig Extension. I would like to check if my variable match a regex. But i Got error.

My twig extension Class:

<?php
// src/GL/HomeBundle/Twig/LastNameExtension.php
namespace GL\HomeBundle\Twig;

class LastNameExtension extends \Twig_Extension
{
    public function getFunctions()
    {  
        return array(
            new \Twig_SimpleFunction('lastName', 'lastNameFunction')
        );
    }

    public function lastNameFunction($lastName)
    {
        $pattern = "/^[1-9]\d\d\-\d\d\d\-\d\d\-\d\d$/";

        return preg_match($pattern, $lastName);
    }

    public function getName()
    {
        return 'lastName';
    }
}
?>

And part of my services.xml file

<services>
    <service id="gl.twig.lastName" class="GL\HomeBundle\Twig\LastNameExtension">
        <tag name="twig.extension" />
    </service>
</services>

The error i got is: : Error: Call to undefined function lastNameFunction() in C:\xampp\htdocs\wp_ubezpieczenia\app\cache\dev\twig\10\4c\8503d697949a099f75aa8c4c41a2.php line 156

I will be very gratefull for any help with this.

Upvotes: 0

Views: 1961

Answers (2)

Ahmed Gaber
Ahmed Gaber

Reputation: 708

use

'lastName'=> new \Twig_Function_Method($this, 'lastNameFunction') instead

and call function in twig with

{{ lastName(myvalue) }}

Upvotes: -1

Stefano Sala
Stefano Sala

Reputation: 907

Replace new \Twig_SimpleFunction('lastName', 'lastNameFunction') with new \Twig_SimpleFunction('lastName', array($this, 'lastNameFunction')), otherwise you are calling the function "lastNameFunction", not the method "LastNameExtension::lastNameFunction".

Upvotes: 3

Related Questions