Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : use translator in a twig filter extension

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 ?

like image 899
svassr Avatar asked Dec 01 '22 05:12

svassr


1 Answers

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
like image 199
lisachenko Avatar answered Dec 04 '22 02:12

lisachenko