现在是个国际化的时代,软件程序如果能够支持多国语言,想必可以有效地加快传播速度。让软件程序拥有多国语言的能力有很多种方式,像是使用相依于操作系统环境本身所提供的 Locale 机制的工具,再搭配语言设置档,例如 GNU 的 gettext 工具搭配 PO 和 MO 档。或是使用能跨操作系统的独立函数库和语言设置档,例如 Fluent 搭配其定义好的特殊语法的语言设置档。当然也可以很单纯地在程序内将所有的文字使用某种 key-value 的数据结构来保存,在程序运行阶段输出文字的时候再决定要使用哪个语系实体的值。
笔者在以前使用 PHP 做开发的时候都是使用 PO 和 MO 档,但访问它们实在是太麻烦了。所以后来使用 Java 做开发时,就直接改用 key-value 的数据结构来保存多国语言用的文字,直接把文字以 hardcode 的形式写在一个独立的源代码文件内,虽然很方便,但不太好修改,因为一旦修改就要进行重新编译的动作。再后来用 Node.js 做开发时,决定改用 JSON 格式作为语言设置档,在程序初始化的时候就将 JSON 数据转成 key-value 的数据结构来保存,经过一段时间的尝试,发现这样的方式是最简单、最容易维护、且又可以轻松跨操作系统的,甚至还能够在不同编程语言间或是网页浏览器上无痛共享相同的 JSON 语言设置档,也不用专门为了搞多国语言又要去学习新的工具和语法!至于开发 Android 时,多国语言文字的部份笔者还是只靠那难用的 XML 文件。
那么,在 Rust 上要如何实现以 JSON 格式作为语言设置档的多国语言功能呢?
JSON Get Text
「JSON Get Text」是笔者开发的套件,可以利用 JSON 格式作为语言设置档,让 Rust 程序轻松支持多国语言。
Crates.io
Cargo.toml
JSON 语言设置档
JSON 语言设置档是一个 JSON 对象的纯文字文件,键值对应的值通常是一个字符串,但是也可以是其他任意的 JSON 值。文件名称随意,方便辨识即可,一般会使用 Locale 格式的字符串,例如 en_US,再搭配 JSON 文件的扩展名 .json。以下举例美国英文和繁体中文的语言设置档撰写的方式:
{
"hello": "Hello, world!",
"rust": "Rust!"
}
{
"hello": "哈啰,世界!"
}
JSON Get Text 拥有预设语言的功能,所有非预设语言的语言设置档的键值均必须包含在预设语言的语言设置档中。以这个例子来说,我们设置 en_US.json 为预设语言,所以 en_US.json 可以拥有 zh_TW.json 所没有的 rust 键值。
创建语库(Context)与搜索文字
json-gettext 这个 crate 底下的 JSONGetText 结构体的每个实体即为一个多国语库,在同一支 Rust 程序中,可以创建多个 JSONGetText 结构实体来创造不同的多国语库。如果要创建 JSONGetText 结构实体,除了可以使用 json-gettext 这个 crate 底下的 JSONGetTextBuilder 结构实体外,一般情况下会比较建议直接使用 static_json_gettext_build 宏。
static_json_gettext_build 宏的第一个参数为预设的语言名称,后面要接分号 ;。接下来的参数两两一组,中间以 => 连接,至少要有一组。每一组的第一个参数表示一个语言的名称,可以随意取,能够辨识即可。第二个参数表示该语言名称的语言设置档路径,路径相对于 CARGO_MANIFEST_DIR 也就是 Cargo.toml 文件的所在目录的路径。static_json_gettext_build 宏在编译阶段,就会将 JSON 文件一同编译进程式可执行文件中。
假设 Cargo.toml 文件位于 /path/to 目录中,我们将 en_US.json 和 zh_TW.json 放置在 /path/to/langs 下,范例程序如下:
#[macro_use] extern crate json_gettext;
let ctx = static_json_gettext_build!(
"en_US";
"en_US" => "langs/en_US.json",
"zh_TW" => "langs/zh_TW.json"
)
.unwrap();
assert_eq!("Hello, world!", get_text!(ctx, "hello").unwrap());
assert_eq!("哈啰,世界!", get_text!(ctx, "zh_TW", "hello").unwrap());
透过 get_text 宏,第一个参数传入要使用的语库(JSONGetText 结构实体),第二个参数传入要使用的语言名称,如果不传的话则表示使用预设的语言名称。第三个参数(若不指定语言名称,则为第二个参数)则是传入要寻找的文字或其它 JSON 值的键值。如果有找到值,就会回传 Option 枚举的 Some 变体,其包裹的值的类型为 json-gettext 这个 crate 底下的 JSONGetTextValue 枚举。假如无法在指定的语言名称,找到指定的键值时,则会尝试去预设的语言名称找同样的键值。如果还是找不到,则会回传 Option 枚举的 None 变体。
如果想要一次取得多个键值对应的值,可以直接替 get_text 宏加上更多参数,传入更多的键值。此时 get_text 宏回传的 Option 枚举的 Some 变体就不会只单纯包裹 JSONGetTextValue 枚举的实体,而会是 HashMap<&str, JSONGetTextValue>。范例程序如下:
#[macro_use] extern crate json_gettext;
use std::collections::HashMap;
use json_gettext::JSONGetTextValue;
let ctx = static_json_gettext_build!(
"en_US";
"en_US" => "langs/en_US.json",
"zh_TW" => "langs/zh_TW.json"
)
.unwrap();
let map_en: HashMap<&str, JSONGetTextValue> = get_text!(ctx, "en_US", "hello", "rust").unwrap();
assert_eq!(&"Hello, world!", map_en.get("hello").unwrap());
assert_eq!(&"Rust!", map_en.get("rust").unwrap());
let map_de: HashMap<&str, JSONGetTextValue> = get_text!(ctx, "de", "hello", "rust").unwrap();
assert_eq!(&"Hello, world!", map_de.get("hello").unwrap());
assert_eq!(&"Rust!", map_de.get("rust").unwrap());
let map_zh: HashMap<&str, JSONGetTextValue> = get_text!(ctx, "zh_TW", "hello", "rust").unwrap();
assert_eq!(&"哈啰,世界!", map_zh.get("hello").unwrap());
assert_eq!(&"Rust!", map_zh.get("rust").unwrap());
Rocket 框架支持
Rocket 是 Rust 的一个 Web 框架(Web Framework),如果想要让 Rocket 能够支持多国语言的话,可以考虑与这个 JSON Get Text 一同使用,程序如下:
#[macro_use] extern crate json_gettext;
#[macro_use] extern crate rocket;
use rocket::response::Redirect;
use rocket::State;
use json_gettext::JSONGetText;
#[get("/")]
fn index(ctx: &State<JSONGetText>) -> Redirect {
Redirect::temporary(uri!(hello(lang = ctx.get_default_key())))
}
#[get("/<lang>")]
fn hello(ctx: &State<JSONGetText>, lang: String) -> String {
format!("Ron: {}", get_text!(ctx, lang, "hello").unwrap().as_str().unwrap())
}
#[launch]
fn rocket() -> _ {
let ctx = static_json_gettext_build!(
"en_US";
"en_US" => "langs/en_US.json",
"zh_TW" => "langs/zh_TW.json"
)
.unwrap();
rocket::build().manage(ctx).mount("/", routes![index, hello])
}
不过由于 static_json_gettext_build 宏在编译阶段就会把 JSON 语言档一同编译进 Rocket 应用程序中,因此在开发这个 Rocket 应用程序时,一旦要套用修改后的 JSON 语言档,就必须得重新编译整个 Rocket 应用程序才行,这样效率实在不是很好。为了解决这个问题,可以激活 JSON Get Text 的 rocket 特色,使其能与 Rocket 框架兼容。Cargo.toml 设置档的写法如下:
[dependencies.json-gettext]
version = "*"
features = ["rocket"]
然后用 static_json_gettext_build_for_rocket 宏来替代 static_json_gettext_build 宏,JSONGetTextManager 结构体来替代 JSONGetText 结构体,程序如下:
#[macro_use] extern crate json_gettext;
#[macro_use] extern crate rocket;
use rocket::State;
use rocket::response::Redirect;
use json_gettext::JSONGetTextManager;
#[get("/")]
fn index(ctx: &State<JSONGetTextManager>) -> Redirect {
Redirect::temporary(uri!(hello(lang = ctx.get_default_key())))
}
#[get("/<lang>")]
fn hello(ctx: &State<JSONGetTextManager>, lang: String) -> String {
format!("Ron: {}", get_text!(ctx, lang, "hello").unwrap().as_str().unwrap())
}
#[launch]
fn rocket() -> _ {
rocket::build()
.attach(static_json_gettext_build_for_rocket!(
"en_US";
"en_US" => "langs/en_US.json",
"zh_TW" => "langs/zh_TW.json"
))
.mount("/", routes![index, hello])
}
如此一来,在使用非 release 模式来编译 Rocket 程序的时候,就不会把 JSON 语言档也跟着编译进 Rocket 应用程序中,而且一旦 JSON 语言档有进行修改的话,JSONGetTextManager 会自动做重新加载的动作。
如果您还不会 Rocket 框架,可以参考《Rocket 入门指南》系列文章。
unic-langid 套件支持
unic-langid 套件提供了用来表示语言及地区的结构体,有着不错的性能,所以很适合拿来当作 JSONGetText 多国语库的键值,就不需要去做字符串比对了。想要使用 unic-langid 套件提供的结构体来作为键值类型,可以激活 json-gettext 的 language_region_pair、language 或是 region 特色,键值类型会分别变成 (Language, Option<Region>)、Language、Region。
在这个情况下,json_gettext 提供的 key 宏可以直接将定数字串转成键值,用起来会很方便。
例如:
[dependencies.json-gettext]
version = "*"
features = ["language_region_pair", "rocket"]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_accept_language;
#[macro_use]
extern crate json_gettext;
use rocket::State;
use rocket_accept_language::unic_langid::subtags::Language;
use rocket_accept_language::AcceptLanguage;
use json_gettext::{JSONGetTextManager, Key};
const LANGUAGE_EN: Language = language!("en");
#[get("/")]
fn index(ctx: &State<JSONGetTextManager>, accept_language: &AcceptLanguage) -> String {
let (language, region) =
accept_language.get_first_language_region().unwrap_or((LANGUAGE_EN, None));
format!("Ron: {}", get_text!(ctx, Key(language, region), "hello").unwrap().as_str().unwrap())
}
#[launch]
fn rocket() -> _ {
rocket::build()
.attach(static_json_gettext_build_for_rocket!(
key!("en");
key!("en") => "langs/en_US.json",
key!("zh_TW") => "langs/zh_TW.json",
))
.mount("/", routes![index])
}
