When creating multilingual application, you will probably need to render the same page or form in various languages.

The Nette Framework defines for this purpose a translation interface Nette\Localization\Translator, which has a single method translate(). It receives a $message, which is usually a string, and any other parameters. Its job is to return the translated string.

There is no default implementation in Nette, you can choose from several ready-made solutions according to your needs, which you will find on Componette. See their documentation to learn how to configure the translator.

You can then get translator in your code by passing it using dependency injection.

As of nette/utils version 3.2, the interface name is Nette\Localization\Translator, ie without the prefix I.

Form Translation

Forms support printing text via a translator. You set it using the method setTranslator():


From this point on, all labels but also all error messages or select box items get translated into another language.

For individual form controls, it is still possible to set another translator or completely turn the translation off using the null value:

$form->addSelect('carModel', 'Model:', $cars)

For validation rules, specific parameters are also passed to the translator, for example for rule:

$form->addPassword('password', 'Password:')
	->addCondition($form::MIN_LENGTH, 'Password must be at least %d characters long', 8);

the translator is called with the following parameters:

$translator->translate('Password must be at least %d characters long', 8);

and thus can choose the correct plural form od word characters according to the number.

Template Translation

In Latte templates, you can add translator as a filter:

$latte->addFilter('translate', [$translator, 'translate']);

The method setTranslator() can also be used in presenters:

protected function beforeRender(): void

Then the translator can be used as other filters:

<a href="basket">{='Basket'|translate}</a>

There is also an abbreviation, underscore tag:

<a href="basket">{_'Basket'}</a>

You can use an alternative pair notation:

<a href="order">{_}Order{/_}</a>
Improve this page