Simple and lightweight translator for Nette Framework, providing localization support using NEON translation files.
- PHP 8.3 or higher
- composer
composer require drago-ex/translator
Register the Drago\Localization\DI\TranslatorExtension
in your Nette project by adding the following
configuration to your neon
file:
extensions:
- Drago\Localization\DI\TranslatorExtension(translateDir: %appDir%/locale)
To use the translator in your presenter, add the TranslatorAdapter
trait:
use Drago\Localization\TranslatorAdapter
You can access the currently set language using the following property:
$this->lang;
To get the translator instance, use the getTranslator
method:
$this->getTranslator();
Translation files should be written in the NEON format. For example:
"Hello, world!": "Hello, world!"
You can translate strings directly in your Latte templates using the following syntax:
{_"Hello, world!"}
{* Using a filter for translation *}
{$var|translate}
To use translations in forms, simply set the translator for the form:
$form->setTranslator($this->getTranslator());
Set up your routes to support language prefixes. For example, you can define routes with language codes:
$router->addRoute('[<lang=en cs|en>/]<presenter>/<action>', 'Presenter:action');
To switch between languages in your templates, you can use n:href to pass the selected language:
<a n:href="this, 'lang' => 'cs'">Czech</a>
<a n:href="this, 'lang' => 'en'">English</a>