Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use translate helper in controllers in zend framework 2

Is there any possible way to translate strings in controllers instead of view?

Right now, in my controllers, if I pass strings like :

public function indexAction() {
    return array('message' => 'example message');
}

It will be translated in index.phtml

<?php print $this->translate($message);?>

It works well, but poeditor unable to find strings from controller files

Guess it would be cool if I can use something like :

public function indexAction() {
    return array('message' => $view->translate('example message'));
}

in controllers

Thanks in advance for help

like image 415
Sanju Avatar asked Nov 27 '22 09:11

Sanju


1 Answers

To use view helper in controller, you can use 'getServiceLocator'

$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('helperName');

Either you can use php getText function ___('my custom message') and add "_" as sources keyword in poedit (in catalog properties) so poedit will filter strings from controller. eg:

array('message' => _('my custom message'));

And as per your code, you can use helper directly like this

$translate = $this->getServiceLocator()->get('ViewHelperManager')->get('translate');

array('message' => $translate('my custom message'));
like image 182
webcoder Avatar answered Dec 11 '22 09:12

webcoder