I18n(國際化)
ll/api/i18n/ · 通用
概述
I18n 模塊提供了國際化和本地化支持,採用簡單的鍵值翻譯系統。支持從文件加載翻譯、運行時更新翻譯,以及通過用戶自定義字面量進行編譯期檢查的格式化字符串。
頭文件
| 頭文件 | 說明 |
|---|---|
ll/api/i18n/I18n.h | I18n 管理器和翻譯字面量 |
核心類
I18n
翻譯管理器單例。
C++
namespace ll::i18n {
class I18n {
public:
Expected<> load(std::filesystem::path const& path) noexcept;
void clear();
void set(std::string_view localeCode, std::string_view key, std::string_view value);
std::string_view get(std::string_view key, std::string_view localeCode) const;
};
I18n& getInstance();
std::string_view getDefaultLocaleCode();
}用戶自定義字面量
_tr — 使用默認語言翻譯
C++
using namespace ll::literals::i18n_literals;
auto msg = "hello.world"_tr(); // 无参数
auto greeting = "hello.user"_tr("Alice"); // 带格式化参数_trl — 使用指定語言翻譯
C++
auto msg = "hello.world"_trl("zh"); // 中文
auto greeting = "hello.user"_trl("en", "Bob"); // 英文带参数使用方法
加載翻譯
load() 函數接受目錄路徑或 JSON 文件路徑:
方式 1:目錄中的獨立語言文件
在目錄中為每種語言創建單獨的 JSON 文件:
Text Only
lang/
├── en.json
├── zh.json
└── ja.json每個文件僅包含該語言的翻譯:
en.json:
JSON
{
"hello.world": "Hello, World!",
"hello.user": "Hello, {}!",
"item.count": "You have {} items"
}zh.json:
JSON
{
"hello.world": "你好,世界!",
"hello.user": "你好,{}!",
"item.count": "你有 {} 个物品"
}加載目錄:
C++
#include "ll/api/i18n/I18n.h"
#include "ll/api/mod/Mod.h"
void loadTranslations(ll::mod::Mod& mod) {
auto& i18n = ll::i18n::getInstance();
// 从目录加载所有语言文件
auto result = i18n.load(mod.getLangDir());
if (!result) {
mod.getLogger().error("加载翻译失败");
}
}方式 2:包含所有語言的單個 JSON 文件
創建一個 JSON 文件,以語言代碼作為頂層鍵:
translations.json:
JSON
{
"en": {
"hello.world": "Hello, World!",
"hello.user": "Hello, {}!",
"item.count": "You have {} items"
},
"zh": {
"hello.world": "你好,世界!",
"hello.user": "你好,{}!",
"item.count": "你有 {} 个物品"
}
}加載文件:
C++
#include "ll/api/i18n/I18n.h"
#include "ll/api/mod/Mod.h"
void loadTranslations(ll::mod::Mod& mod) {
auto& i18n = ll::i18n::getInstance();
// 加载包含所有语言的单个文件
auto result = i18n.load(mod.getLangDir() / "translations.json");
if (!result) {
mod.getLogger().error("加载翻译失败");
}
}使用翻譯
C++
#include "ll/api/i18n/I18n.h"
using namespace ll::literals::i18n_literals;
void greetPlayer(std::string const& name) {
// 使用默认语言
auto msg = "hello.user"_tr(name);
// msg == "Hello, Alice!" 或 "你好,Alice!" 取决于默认语言
}
void showItemCount(int count) {
auto msg = "item.count"_tr(count);
}運行時更新翻譯
C++
#include "ll/api/i18n/I18n.h"
void addTranslation() {
auto& i18n = ll::i18n::getInstance();
i18n.set("en", "custom.key", "Custom message");
i18n.set("zh", "custom.key", "自定义消息");
}顯式選擇語言
C++
using namespace ll::literals::i18n_literals;
void showInChinese() {
auto msg = "hello.world"_trl("zh");
// msg == "你好,世界!"
}相關模塊
- Mod(模組系統) —
Mod::getLangDir()返回語言目錄