sonix-i18n
A Rust internationalization library inspired by i18next - Created by SonickSeven
Installation
Add the following to your Cargo.toml file:
[dependencies]
sonix-i18n = "0.1.1"
Usage
1. Create your locale files
This library uses the same structure as i18next. You need to create a JSON
file for each language you want to support. The files should be structured as
follows:
locales/en/common.json
{
"welcome": "Welcome to our application {{user}}!",
"greet": "Hello"
}
locales/es/common.json
{
"welcome": "¡Bienvenido a nuestra aplicación {{user}}!",
"greet": "¡Hola!"
}
2. Load the locales and initialize the library
You need to load the content of your locale files into a HashMap and then pass
it to the init function.
use std::collections::HashMap;
use serde_json::Value;
use sonix_i18n::{init, t};
fn main() {
let mut resources = HashMap::new();
let en_common: Value = serde_json::from_str(include_str!("../locales/en/common.json")).unwrap();
let mut en_map = HashMap::new();
en_map.insert("common".to_string(), en_common);
resources.insert("en".to_string(), en_map);
let es_common: Value = serde_json::from_str(include_str!("../locales/es/common.json")).unwrap();
let mut es_map = HashMap::new();
es_map.insert("common".to_string(), es_common);
resources.insert("es".to_string(), es_map);
init(resources, Some("en".to_string())).unwrap();
println!("{}", t!("common:welcome", {"user": "John"}));
println!("{}", t!("common:greet")); }
3. Using the t! macro
The t! macro is the main way to get translations. It takes a key as an
argument, which is a string that identifies the translation you want to get.
- Basic usage:
t!("namespace:key")
- With arguments:
t!("namespace:key", {"arg": "value"})
4. Changing the language
You can change the language at runtime using the change_language function.
use sonix_i18n::{change_language, t};
fn main() {
println!("{}", t!("common:welcome", {"user": "John"}));
change_language("es").unwrap();
println!("{}", t!("common:welcome", {"user": "John"})); }