How to create a custom Twig function in Symfony 2

Hi all,

Did you ever wonder of creating your own custom twig function. For instance, assume that you are displaying set of url’s in your view (twig) file. Suddenly you want all or some of your url’s to be opened in a new tab once clicked. We all know this can easily be done by having the target attribute in anchor tag such as <a href = “link” target=”_blank”>Text</a>. This seems to be pretty straight forward. But if you want to add or remove this target attribute one day in all of your urls, it will be nightmare to change all down the line. Instead, if you have used a custom twig function to add this property to the link and use that function instead of html anchor tag in the twig file, things will be much easier when it comes to changing things later.

Let’s see how we do this,

  • To achieve what we wanted, we want to create a new class (which extends Twig_Extension). Create a new PHP class and save it in a your project. Define the class name extending ‘\Twig_Extension’. (Make sure you add the namespace)
  • ┬áIn the class file, you need to declare two functions. One is to register the custom function and one is to return the name of the class as a string. The first function you need to add is ‘getFilters()’ and register your custom function there.

public function getFilters()

{
return array(
new \Twig_SimpleFilter(‘custom_website’, array($this, ‘customWebsiteFilter’)),
);
}

Continue reading

Share