Crate r18

source ·
Expand description

🔞

r18 is a crate intends to simplify the internationalisation of Rust projects.

MSRV >= 1.70.0 (stable)

Usage

Add r18 as your project dependency:

[dependencies]
r18 = "*"

Create a JSON translation file whose filename follows IETF BCP 47 language tag, like below:

// PATH: ./tr/zh-CN.json
{
    "Hello, {}": "你好,{}"
}

Then add init to the global scope of your code with the directory where translation files in (in following example is ./tr).

r18::init!("tr");

After initialising the r18, use auto_detect to detect locale and load translation model automatically.
If you want, you can use set_locale to set locale manually.
After above process, use tr to get your text which has been translated.

r18::init!("tr");

fn main() {
    r18::auto_detect!(); // get locale & set

    let name = "ho-229";
    println!("{}", r18::tr!("Hello, {}", name));

    // reset locale to disable translation
    r18::set_locale!("");
    assert_eq!("Hello, ho-229", r18::tr!("Hello, {}", name));
}

Fallback Configuration

Sometimes your translation may not fully match the user’s locale, but usually, this doesn’t mean that your translations cannot be used. In that case, we need the fallback feature.

By default, if the translation does not match the user’s locale, r18 will fallback to the translation which is the same language by the highest alphabetical order.

You can also specify a fallback translation for a language in config.json which placed with other translation files.

eg.

{
    "fallback": {
        "zh": "zh-TW"
    }
}

Macros

  • Automatically sets the current locale.
  • Generate translation models and functions set_locale and locale to setup r18 environment with given translation directory.
  • Returns the current locale.
  • Sets the current locale.
  • Translate and content formatting.

Functions

  • Translate content with the locale setting and given prefix.