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?
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.
Instead of getFilters, override getFunctions and use Twig_Function_Method instead of Twig_Filter_Method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With