7

I've noticed in many tutorials for constructing block plugins,

$this->t('text')

is used to create translatable text, especially in the block form function. However using

t('text') 

doesn't produce any errors. Is there any difference between using either of these? And if there isn't, what's best practice?

6

To be exact on your question: there's no difference in internal implementation.

But as a best practice, you should be using $this->t instead of the global t wherever possible. If you check the function, t is returning a new TranslateableMarkup object.

If your class says $this->t is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

Using this trait will add t() and formatPlural() methods to the class. These must be used for every translatable string, similar to how procedural code must use the global functions t() and \Drupal::translation()->formatPlural(). This allows string extractor tools to find translatable strings.

If the class is capable of injecting services from the container, it should inject the 'string_translation' service and assign it to $this->stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).

|improve this answer|||||
4

The documentation for t() states:

When possible, use the \Drupal\Core\StringTranslation\StringTranslationTrait::t(). Otherwise create a new \Drupal\Core\StringTranslation\TranslatableMarkup object directly.

It doesn't explain the reason for this, but if you look at the comment on the documentation page, it will give you a reason for using that trait method, or that class.

Classes can be tested individually with PHPUnit, which runs without bootstrapping core, but the t() function is only available when core is bootstrapped.
Using $this->t() and StringTranslationTrait allows the translation to be mocked, so the class can be tested in isolation with PHPUnit.

|improve this answer|||||

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.