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.

1 Answer 1

1

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.');
  }
}
3
  • 1
    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
    Commented May 20, 2016 at 9:14
  • @Berdir how would I exactly inject the stringTranslationTrait as a service? Post an answer please
    – Cesc
    Commented May 20, 2016 at 9:34
  • @Cesc check out the code and answer of this question drupal.stackexchange.com/questions/239239/… It comes down to where the trait gets it's service. Best practices and all that. Commented Aug 24, 2021 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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