我正在尝试在这样的自定义 Twig 过滤器中使用翻译
public function formatTime($timestamp)
{
$str = date('j %\m%',$timestamp);
$str = str_replace($str, '%m%', $this->get('translator')->trans('month'.date('m', $timestamp) ) );
return $str;
}
offcourse get 是未知功能。
我应该让我的扩展了解环境还是简单地请求翻译类以使其可用?
最佳答案
您可以注入(inject) translator
服务到你的类(class):
<service id="acme.extension" class="Acme\Twig\Extensions\FormatterExtension">
<tag name="twig.extension"/>
<argument type="service" id="translator"/>
</service>
然后将翻译器的实例存储在 protected 字段中并稍后使用:
public function formatTime($timestamp)
{
$str = date('j %\m%',$timestamp);
$str = str_replace($str, '%m%', $this->translator->trans('month'.date('m', $timestamp) ) );
return $str;
}
UPD1: YAML 服务定义的配置:
acme.extension:
class: Acme\Twig\Extensions\FormatterExtension
arguments: [@translator]
tags:
- name: twig.extension
关于Symfony2 : use translator in a twig filter extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102344/