v2.0.0
What's New
- Add multiple formats
*.{yml,yaml,json, toml}
#38 - Add
Backend
trait for allows us to customize the difference translations storage. - Rewrite code to generate for use
backend
as code result to allows extending backend. - Add public API
i18n()
method, this is Backend instance.
Breaking Changes
available_locales
method has removed, userust_i18n::available_locales!()
instead.- Refactor crate
rust_i18n_support
internal APIs, private some methods.
How to extend backend
Write a struct that implements the Backend
trait, and then implement the methods in the trait.
use rust_i18n::Backend;
pub struct MyBackend {
trs: HashMap<String, HashMap<String, String>>,
}
impl MyBackend {
fn new() -> Self {
let trs = HashMap::new();
trs.insert("en".to_string(), {
let mut trs = HashMap::new();
trs.insert("hello".to_string(), "Hello MyBackend".to_string());
trs.insert("welcome".to_string(), "Welcome to use MyBackend".to_string());
trs
});
return Self {
trs
};
}
}
impl Backend for MyBackend {
fn available_locales(&self) -> Vec<String> {
todo!()
}
fn translate(&self, locale: &str, key: &str) -> Option<String> {
// Write your own lookup logic here.
// For example load from database
return self.trs.get(locale)?.get(key).cloned();
}
}
Now replace the default backend with your own backend.
rust_i18n::i18n!(fallback = "en", backend = MyBackend::new());
fn main() {
t!("hello");
// "Hello MyBackend"
t!("welcome");
// "Welcome to use MyBackend"
}
This also will load local translates from
./locales
path, but your ownMyBackend
will priority than it.