r18

Crates.ior18
lib.rsr18
version0.5.0
sourcesrc
created_at2022-12-22 06:17:05.717384
updated_at2023-08-29 11:54:42.513825
descriptionA simply I18n crate for Rust.
homepage
repositoryhttps://github.com/Limit-LAB/r18
max_upload_size
id743695
size12,104
Ho 229 (ho-229)

documentation

README

🔞

crate.io docs build

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 (you can generate it by CLI Tool):

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

Then add r18::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!("{}", tr!("Hello, {}", name));

    // reset locale to disable translation
    r18::set_locale!("");
    assert_eq!("Hello, ho-229", 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"
    }
}

You can find a complete example here. You can run the example with following command:

cargo run -p example

CLI Tool Usage

Run the below command to install cargo r18:

cargo install cargo-r18

After creating the translation directory and writing code as above, you can run the following command to generate translation files (eg. TODO.zh-CN.json):

cargo r18 generate zh-CN

Additionally, you can generate todo files of untranslated texts after changing your source by:

cargo r18 update

LIMITATION: cargo r18 is only scanning macros named init and tr that it can NOT recognise which belong to r18 or not, you should make sure that no similar macros are named in your source before using cargo r18.

Run cargo r18 -h for more options.

Credit

Commit count: 62

cargo fmt