Internationalization (i18n)

ferrite-i18n loads catalog files and resolves translated message keys at runtime, with an I18nService you inject anywhere.

Enable it

fr add i18n
#[module(imports = [I18nModuleImpl])]
pub struct AppModule;

Requires the I18n feature flag:

ferrite = { version = "=0.1.0", features = ["I18n"] }

Catalogs

Place JSON catalogs where the loader looks (default locales/), named by locale code:

locales/
  en.json   { "welcome": "Welcome, {name}!" }
  vi.json   { "welcome": "Xin chào, {name}!" }
  fr.json   { "welcome": "Bienvenue, {name}!" }
EnvDefault
LOCALE_DIRlocales
DEFAULT_LOCALEen

I18nModuleImpl implements OnApplicationBootstrap and loads all catalogs at startup.

I18nService

Inject it wherever translations are needed:

use ferrite_i18n::I18nService;

#[injectable]
pub struct MailService {
    i18n: I18nService,
}

impl MailService {
    #[inject]
    pub fn new(i18n: I18nService) -> Self {
        Self { i18n }
    }

    pub fn subject(&self, locale: &str, name: &str) -> String {
        self.i18n.format("mail.welcome", locale, &[("name", name)])
    }
}
MethodPurpose
resolve(key, locale)Look up a key
format(key, locale, params)Look up + substitute {param} placeholders
has_key(key, locale)Presence check
available_locales()Loaded locales
default_locale()The configured default

format falls back to the default locale when a key is missing in the requested locale.

From HTTP

Resolve the locale from a header or query then pass it along:

use axum::extract::Query;

#[get("/greet")]
pub async fn greet(
    &self,
    Query(params): Query<HashMap<String, String>>,
    headers: HeaderMap,
) -> Result<Json<String>, HttpError> {
    let locale = headers
        .get("accept-language")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("en");
    Ok(Json(self.i18n.format("welcome", locale, &[("name", "Ada")]).into()))
}

Next steps