Localization
Yabasi provides a powerful and flexible localization system for creating multilingual applications. The framework uses JSON-based language files and offers an intuitive API for managing translations.
Configuration
First, set your application's default and fallback locales in your configuration file:
return [
'app' => [
'locale' => 'en',
'fallback_locale' => 'en',
],
];
Language Files
Create JSON language files in the storage/lang
directory. Each language should have its own file:
{
"welcome": "Welcome to our application",
"auth.failed": "These credentials do not match our records",
"users.greeting": "Hello, :name!",
"items.count": "You have :count items"
}
Basic Usage
You can use the translation helper function __()
or the Translator class directly:
// Using helper function
echo __('welcome');
// Using with parameters
echo __('users.greeting', ['name' => 'John']);
// Using Translator class
$translator = $container->get(Translator::class);
echo $translator->get('welcome');
Using in Twig Templates
The translation function is also available in Twig templates:
<h1>{{ "{{ __('welcome') }}" }}</h1>
<p>{{ "{{ __('users.greeting', {'name': user.name}) }}" }}</p>
Switching Locales
You can change the application's locale at runtime:
$translator = $container->get(Translator::class);
// Switch to Spanish
$translator->setLocale('es');
Pluralization
Handle pluralization in your translations using the count parameter:
{
"items.zero": "No items found",
"items.one": "One item found",
"items.many": ":count items found"
}
Best Practices
- Use dot notation to organize translations hierarchically
- Always provide a fallback locale for missing translations
- Keep translation keys lowercase and use dots for namespacing
- Use meaningful key names that describe the content
- Group related translations together
Remember to create language files for all supported locales before deploying your application. Missing translations will fall back to the default locale.