lliure / twig-translate
Twig extension for translation using 'yaml'
Requires
- php: >= 8.0
- ext-yaml: *
- twig/twig: ^3.0
README
This extension allows translation of messages in Twig templates using yaml files. It's useful for projects that require multi-language support.
Example Usage
Installation:
Before you begin, make sure you have installed the package in your project using Composer:
composer require lliure/twig-translate
Configuration:
require_once 'vendor/autoload.php'; use Twig\TwigFilter; $loader = new \Twig\Loader\FilesystemLoader('views'); $twig = new \Twig\Environment($loader); // Create an instance of the translation class, passing the desired language $myTwigFilters = new \TwigTranslate\Translate('pt_BR'); // Add the extension to the Twig environment $twig->addExtension($myTwigFilters); echo $twig->render('home.html', ['name' => 'Jeison']);
You can also specify the domain you want to use.
$myTwigFilters = new \TwigTranslate\Translate('pt_BR', 'location/of/translate/files', ['home']);
By default, a domain with the same name as the specified language is always loaded unless you specify a different one.
For example, the default translation file path for 'pt_BR' would be:
location/of/translate/files/pt_BR/pt_BR.yml
You can specify the 'home' domain as shown in the code to load a different translation domain.
Usage in Twig Template:
In your Twig templates, you can use the
translate
filter or_
to translate messages:{{ 'Hello'|translate }} {{ name }}, {{ 'Goodbye'|_ }}
Using Variables
In YAML, you can define variables within "%" to make your text dynamic:
"Displaying page %currentPage%": "Displaying page %currentPage%"
In Twig, you can incorporate these variables into the translated text as follows:
{{ 'Displaying page %currentPage%'|translate({'currentPage': data.pagination.currentPage}) }}
This allows you to insert the value of the
currentPage
variable into the translated text, making it personalized and dynamic.
Translation Files
Translations are saved in YAML files.
Example .yaml File
hello: Olá
goodbye: Até mais
Location of translate Files
.yaml files should be stored in a specific directory structure:
pt_BR/home.yaml
By default, the configured folder is:
etc/locale
However, you can change the folder path in the extension call. The final path will be a combination of the configured path and the language:
etc/locale/pt_BR/home.yaml
Make sure to adjust the path as needed to match your project's directory structure.
Contribution
If you'd like to contribute to this package, please feel free to open an issue or submit a pull request. We appreciate your collaboration!