Fluent是一种新的I18n实现规范。在Rust中有实现fluent-rs项目。本篇介绍以这种技术实现本地化。
文件结构:
message.ftl:
hello = 您好!世界!
Cargo.toml:
[package]
name = "fluentSample"
version = "0.1.0"
authors = ["许阳 <mksword@1126.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
fluent = "0.10.2"
fluent-resmgr = "0.0.3"
unic-langid = "0.8.0"
main.rs:
use fluent::{FluentBundle, FluentValue, FluentResource, FluentArgs};
use fluent_resmgr::resource_manager::ResourceManager;
use unic_langid::LanguageIdentifier;
fn main() {
let mgr = ResourceManager::new("./resources/{locale}/{res_id}".into());
let langid: LanguageIdentifier = "zh-CN".parse().expect("aa");
let locales = vec![langid.into()];
let resources = vec![ "message.ftl".into()];
let bundle = mgr.get_bundle(locales, resources);
let value = bundle.get_message("hello").unwrap();
let pattern = value.value.expect("ddd");
let mut errors = vec![];
let msg = bundle.format_pattern(&pattern, None, &mut errors);
println!("{}", msg);
}