4 个版本
0.0.3 | 2019 年 10 月 9 日 |
---|---|
0.0.2 | 2019 年 10 月 9 日 |
0.0.1 | 2019 年 10 月 3 日 |
0.0.0 | 2019 年 10 月 3 日 |
#166 在 国际化(i18n)
每月 32 次下载
14KB
167 行
国际化
Rust 中一个简单的编译时 i18n 实现。如果翻译键不存在,它将抛出编译错误,但由于 lang
参数是动态的,如果匹配键未添加该语言,它将 panic。
用法
在你的应用中的某个地方(根目录、src、任何地方)有一个 locales/
文件夹,其中包含嵌套或不嵌套的 .json
文件。它使用 glob 模式 **/locales/**/*.json
来匹配你的翻译文件。
文件应如下所示
{
"err.user.not_found": {
"fr": "Utilisateur introuvable: $email, $id",
"en": "User not found: $email, $id"
},
"err.answer.all": {
"fr": "Échec lors de la récupération des réponses",
"en": "Failed to retrieve answers"
},
"err.answer.delete.failed": {
"fr": "Échec lors de la suppression de la réponse",
"en": "Failed to delete answer"
}
}
可以添加任何数量的语言,但你应该为所有内容提供它们,因为如果在查询键时找不到语言,它将 panic。
在你的应用中,只需调用 t!
宏
fn main() {
let lang = "en";
let res = t!("err.not_allowed", lang);
assert_eq!("You are not allowed to do this", res);
}
你可以使用插值,任何数量的参数都行,但你应该注意它们必须按字母顺序排序。要使用变量,请像这样调用 t!
宏
fn main() {
let lang = "en";
let res = t!("err.user.not_found", email: "me@localhost", id: "1", lang);
assert_eq!("User not found: me@localhost, ID: 1", res);
}
安装
国际化在 crates.io 上可用,将其包含在你的 Cargo.toml
中
[dependencies]
internationalization = "0.0.2"
然后像这样将其包含在你的代码中
#[macro_use]
extern crate internationalization;
或在你想使用宏的地方使用它
use internationalization::t;
注意
如果没有设置 PWD
环境变量,国际化将无法工作。
没有运行时依赖项
~0–410KB