Translation of Forms and Templates

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 of word characters according to the number.

Template Translation

In Latte templates, you can add translator using method setTranslator():

protected function beforeRender(): void
	// ...

Then the translator can be used as filter |translate:

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

There is also an underscore tag:

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

There is a {translate} pair tag for translating parts of the template (since Latte 2.11, previously the {_} tag was used):

<a href="order">{translate}Order{/translate}</a>