Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom function in Twig

Tags:

php

twig

symfony

In my template I want to output the server timezone.

My template has something like

{{ getservertimezone }} 

Then in the services.yml config for that bundle I have

my.twig.extension:     class: My\WebsiteBundle\Extensions\Twig\SomeTemplateHelper     tags:            - { name: twig.extension } 

And my SomeTemplateHelper looks like

namespace My\WebsiteBundle\Extensions\Twig;  class SomeTemplateHelper extends \Twig_Extension {      public function getFilters()      {         return array(             'getservertimezone'  => new \Twig_Filter_Method($this, 'getServerTimeZone'),         );     }           public function getServerTimeZone()     {         if (date_default_timezone_get()) {             return date_default_timezone_get();         } else if (ini_get('date.timezone')) {             return ini_get('date.timezone');         } else {             return false;         }     }      public function getName()     {         return 'some_helper';     }      } 

But I can't call this method unless it's used like a filter: {{ someval | getservertimezone }}; is there a way to just do a straight {{ getservertimezone() }} call?

like image 824
ed209 Avatar asked Nov 07 '12 20:11

ed209


2 Answers

Use getFunctions() instead of getFilters()

public function getFunctions() {     return array(         new \Twig_SimpleFunction('server_time_zone', array($this, 'getServerTimeZone')),     ); } 

Twig filters are used to filter some value.

{{ "some value" | filter_name_here }} 

Btw, you can define both filters and functions in the same class.

like image 55
Vadim Ashikhman Avatar answered Sep 19 '22 19:09

Vadim Ashikhman


Instead of getFilters, override getFunctions and use Twig_Function_Method instead of Twig_Filter_Method.

like image 35
Elnur Abdurrakhimov Avatar answered Sep 19 '22 19:09

Elnur Abdurrakhimov