rust-i18n
rust-i18n is a crate for loading localized text from a set of YAML mapping files. The mappings are converted into data readable by Rust programs at compile time, and then localized text can be loaded by simply calling the provided t!
macro.
The API of this crate is inspired by ruby-i18n and Rails I18n.
Usage
Add crate dependencies in your Cargo.toml:
[]
= "1.4.0"
= "0"
Load macro and init translations in lib.rs
// Load I18n macro, for allow you use `t!` macro in anywhere.
extern crate rust_i18n;
// Init translations for current crate.
i18n!;
Make sure all YAML files (containing the localized mappings) are located in the locales/
folder of the project root directory:
.
├── Cargo.lock
├── Cargo.toml
├── locales
│ ├── en.yml
│ ├── zh-CN.yml
│ └── zh-TW.yml
└── src
└── main.rs
In the YAML files, specify the localization keys and their corresponding values, for example, in en.yml
:
en: # The language code of this mapping file
hello: Hello world # A simple key -> value mapping
messages:
hello: Hello, %{name} # A nested key.sub_key -> value mapping, in this case "messages.hello" maps to "Hello, %{name}"
And example of the zh-CN.yml
:
zh-CN:
hello: 你好世界
messages:
hello: 你好, %{name}
Loading Localized Strings in Rust
Import the t!
macro from this crate into your current scope:
use t;
Then, simply use it wherever a localized string is needed:
t!;
// => "Hello world"
t!;
// => "你好世界"
t!;
// => "Hello, world"
t!;
// => "你好, Jason"
Setting and Getting the Global Locale
You can use rust_i18n::set_locale
to set the global locale at runtime, so that you don't have to specify the locale on each t!
invocation.
;
let locale = locale;
assert_eq!;
set_locale
Debugging the Codegen Process
The RUST_I18N_DEBUG
environment variable can be used to print out some debugging infos when code is being generated at compile time.
Example
A minimal example of using rust-i18n can be found here.
License
MIT