i18n-rs 1.0.0

A Rust library for internationalization (i18n) support
Documentation
  • Coverage
  • 94.12%
    16 out of 17 items documented0 out of 11 items with examples
  • Size
  • Source code size: 18.03 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 489.43 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 20s Average build duration of successful builds.
  • all releases: 20s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • mykhailokrainik

i18n-rs

i18n-rs is a lightweight internationalization helper designed to be embedded in any Rust web framework. It focuses on a familiar JSON-based translation file so you can reuse the dictionaries you already maintain while keeping your web stack framework agnostic.

Features

  • Loads translations from JSON files, strings, or any reader.
  • Automatically flattens nested translation keys using dot notation.
  • Optional fallback language for missing translations.
  • Straightforward API that suits synchronous and async contexts alike.

Installation

Add the crate to your project:

[dependencies]
i18n-rs = "1.0.0"

Translator File Format

The crate expects a JSON object whose top-level keys are language identifiers. Each language contains nested objects and/or string values. Nested keys are automatically flattened using dot notation.

{
  "en": {
    "greeting": {
      "welcome": "Welcome",
      "farewell": "Goodbye"
    }
  },
  "fr": {
    "greeting": {
      "welcome": "Bienvenue"
    }
  }
}

The example above yields the keys greeting.welcome and greeting.farewell.

Usage

use i18n_rs::Translator;

static JSON: &str = r#"{
    "en": {
        "welcome": "Welcome!",
        "farewell": "See you later!",
        "button": {
            "submit": "Submit"
        }
    },
    "es": {
        "welcome": "¡Bienvenido!",
        "button": {
            "submit": "Enviar"
        }
    }
}"#;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let translator = Translator::builder()
        .fallback_language("en")
        .load_from_str(JSON)?;

    assert_eq!(
        translator.translate("es", "button.submit"),
        Some("Enviar")
    );

    // Missing keys gracefully use the fallback language.
    assert_eq!(
        translator.translate_with_fallback("es", "farewell"),
        Some("See you later!")
    );

    Ok(())
}