0
votes

I have implemented a new twig extension and I have some text which had to be translated.

Unfortunately when I use a code label it appears as a sample text.

I mean when twig render this following extension, it displays: 5 entity.years instead of 5 years for example:

class MyExtension extends \Twig_Extension {
public function getFilters()
{
    return array(
        'myextension' => new \Twig_Filter_Method($this, 'myextension'),
    );
}

public function myextension ($myId)
{
        // ....
        // Some operations concerning $myId...
        // ....
    if($myId!=0) { 
        $res = $myId. ' '.'entity.year'; 
    } else { 
        $res = ($months == 0 ? $days.'entity.days' : $months.'entity.months'); 
    } 

    return $res;
}
}

Where entity.years, entity.months, entity.days is defined into my translations folder.

1

1 Answers

1
votes

Inject the translator service into your extension and use it. For example:

class MyExtension extends \Twig_Extension
{
    private $translator;

    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    // ...

    public function myMethod()
    {
        return $this->translator->trans('my_string');
    }
}