Internationalization (i18n)
Rails
Rules
- Use English as I18n#default_locale, and fallback to it when strings are missing in used language.
- Add error reporting for missing translations for development and test environments.
- Always use I18n#l method instead of strftime method. The latter does not localize date & time.
- Create separate files for customizing translations from gems (e.g. device.en.yml)
Tips
- To find untranslated strings easier, patch I18n#t method to always return placeholder string (e.g. “xxx”). This way, untranslated strings will stand out among placeholders.
- If client-side translations are needed, use i18n-js gem.
Structuring translation files
Translations are stored in config/locales
directory, in YAML files. For each language, the main translation file only contains translations that are used in application code. Translations that are used by various libraries are stored in separate corresponding files (e.g. English Devise translations are stored in devise.en.yml, Kaminari - kaminari.en.yml, etc.).
Translation string keys are structured in a way so higher level key is either controller or mailer name, followed by action name, and then by corresponding keys used in that action. Translations for ActiveRecord models, attributes and errors are stored under activerecord
key. Other translations are grouped by their semantic meaning. Translations that are used in javascript are stored under global js
key, followed by bundle name, feature name, and component name.
Example:
en:
activerecord:
attributes:
user:
date_of_birth: 'Date of birth'
...
posts:
index:
title: 'Posts'
show:
header: 'Posted by %{author}'
...
users_mailer:
reminder:
greeting: 'Hello, %{name}'
...
js:
blog_app:
posts:
post:
delete_button:
caption: 'Delete post'
...
iOS
Rules
- Always use NSLocalizedString in code when adding new strings.
- Never split, combine or generate programmatically NSLocalizedString key. Xcode uses static analysis to find string localizations in code, thus dynamically generated keys won’t appear in localization files.
- Include client device locale in each request to the backend server. Use “Api-Locale” key in request’s headers.
Tips
- Strings that are in storyboards are automatically added to localization files by Xcode.
- To export strings for editing, in Xcode select project file, then go to “Editor -> Export For Localization”.
- To import edited strings, in Xcode select project file, then go to “Editor -> Import Localizations”.
- Use
String(format: ...)
when interpolating translated strings. - Info.plist files contain localized system settings (e.g. NSPhotoLibraryUsageDescription).
React applications
- Use react-i18next for translating React Single-Page applications.