I'm trying to use translation in a custom twig filter like this
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 is unknown function. Should I make my Extension aware of the environment or simply request translation class to make it available ?
You can inject a translator
service into your class:
<service id="acme.extension" class="Acme\Twig\Extensions\FormatterExtension">
<tag name="twig.extension"/>
<argument type="service" id="translator"/>
</service>
And then store an instance of translator in the protected field and use it later:
public function formatTime($timestamp)
{
$str = date('j %\m%',$timestamp);
$str = str_replace($str, '%m%', $this->translator->trans('month'.date('m', $timestamp) ) );
return $str;
}
UPD1: configuration for YAML service definition:
acme.extension:
class: Acme\Twig\Extensions\FormatterExtension
arguments: [@translator]
tags:
- name: twig.extension
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