Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

For most tasks you'll find a suitable drupal class to extend from which has $this->t() defined, but if you need to build your own class from scratch best practice would be to use the string translation trait and inject this as service if you use this class in a service context.

Here is an example How to inject translator service in custom services or controllers in Drupal 8 using the StringTranslationTrait to get t() and formatPlural() methods.

Example:

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
class MyClass {
  use StringTranslationTrait;

  /**
   * Constructs a MyClass object.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(TranslationInterface $string_translation) {
    // You can skip injecting this service, the trait will fall back to \Drupal::translation()
    // but it is recommended to do so, for easier testability,
    $this->stringTranslation = $string_translation;
  }

  /**
   * Does something.
   */
  public function doSth() {
    // ...
    $string = $this->t('Something');
    // ...
  }

}

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon