0

I am confused by this one.

I want the translator service injected in my service. The closes thing I've found is this one: Drupal\Core\StringTranslation\TranslationManager; ( https://api.drupal.org/api/drupal/core!lib!Drupal!Core!StringTranslation!TranslationManager.php/class/TranslationManager/8.2.x) but it has no method "t" and it really makes emphasises to not use it's translate function, to use \Drupal\Core\StringTranslation\StringTranslationTrait; instead. But I can't inject this in my service, can I? (how?)

Ultimately, I just want to call t function in my own service.

0

It looks that there is no need to inject anything. Just use a "use" statement inside the class

class MyModuleService {
  use \Drupal\Core\StringTranslation\StringTranslationTrait;

  function a() {
    $this->t('should at least not complaint.');
  }
}
  • You can also extend from ControllerBase and then you get this by default. Note that this falls back to \Drupal::service() in \Drupal\Core\StringTranslation\StringTranslationTrait::getStringTranslation unless you actually do inject that service. So if you want to write unit tests for your class, you might still want to do that. – Berdir May 20 '16 at 9:14
  • @Berdir how would I exactly inject the stringTranslationTrait as a service? Post an answer please – Cesc May 20 '16 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.