0

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.

1
  • It should work. What Symfony version are you using ? Did you cleared the cache completely ? Can you copy paste the code of the line where the error occurs in your cached file ? Commented Oct 9, 2013 at 11:08

2 Answers 2

3

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".

Sign up to request clarification or add additional context in comments.

Comments

-1

use

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

and call function in twig with

{{ lastName(myvalue) }}

1 Comment

Twig_Function_Method is deprecated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.