在 Twig 中使用自定义函数 [英] Using a custom function in Twig
本文介绍了在 Twig 中使用自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的模板中,我想输出服务器时区.
In my template I want to output the server timezone.
我的模板有类似的东西
{{ getservertimezone }}
然后在我拥有的那个包的 services.yml
配置
Then in the services.yml
config for that bundle I have
my.twig.extension:
class: My\WebsiteBundle\Extensions\Twig\SomeTemplateHelper
tags:
- { name: twig.extension }
我的 SomeTemplateHelper
看起来像
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';
}
}
但是我不能调用这个方法,除非它像过滤器一样使用:{{ someval |getservertimezone }}
;有没有办法直接调用 {{ getservertimezone() }}
调用?
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?
推荐答案
使用 getFunctions()
而不是 getFilters()
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('server_time_zone', array($this, 'getServerTimeZone')),
);
}
Twig 过滤器用于过滤某些值.
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.
这篇关于在 Twig 中使用自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文