I18n
Fuwafuwa Framework supports internationalization (i18n) to cater to users from different regions and languages. This allows you to create multilingual applications that adapt to user preferences.
Language and Locale
The framework employs a language and locale system to manage translations. A language code (e.g., 'en', 'id', 'fr') represents the language, while a locale code (e.g., 'en_US', 'id_ID', 'fr_FR') specifies the region or country.
Translation Files
Basic Structure:
Language Directories: Each language is represented by its ISO 639-1 two-letter code (e.g., en, fr, de). These directWithin each language directory, translation files are stored as PHP arrays. The file naming convention is flexible but often follows a logical structure related to the content or module they represent. Example: Within each language directory, translation files are stored as PHP arrays. The file naming convention is flexible but often follows a logical structure related to the content or module they represent. Example:
app/i18n/
en/
common.php
navigation.php
forms/
login.php
registration.php
fr/
common.php
navigation.php
forms/
login.php
registration.php
In this example:
common.php contains general translations used throughout the application.
navigation.php holds translations related to navigation elements.
The forms directory houses translation files for different form elements.
Translation File Format
Translation files are PHP arrays with key-value pairs. The keys represent the original text, and the values represent the translated text. Example:
// app/i18n/en/common.php
<?php
return [
'hello' => 'Hello, world!',
'greeting' => 'Welcome to our website'
];
Using Translations
Fuwafuwa Framework provides a convenient way to translate text using the t() method. This method retrieves the translated text for a given key from the appropriate translation file.
Basic Usage:
- Key Structure: The translation key follows a hierarchical structure, mimicking the organization of your translation files. Separate folders and files in the app/i18n directory translate to a path-like key.
- t() Method: The
t()method takes the translation key as its argument.
Example:
Suppose you want to translate the label "Name" from the forms/registration.php file in the English (en) language directory. Here's how you would achieve this:
Template File (e.g., register.html):
Translation File (app/i18n/en/forms/registration.php):
<?php
return [
'name' => 'Full Name',
];
Explanation:
-
In the template file,
{{ t('forms.registration.name') }}calls thet()method with the key'forms.registration.name'. -
This key matches the structure of the translation file (
forms/registration.php) within the en language directory. -
The
t()method retrieves the corresponding value ('Full Name') from the translation file and replaces the placeholder in the template.