Translator
Translator 是跨框架與執行環境皆一致的單一翻譯介面。
所有翻譯操作皆透過此介面進行。
Translator 僅能透過以下入口存取:
useTranslator()(Client)getTranslator()(Server)
Translator 的方法設計為透過 解構(destructuring) 方式存取。
此介面形式為 Intor 的刻意設計,供靜態分析(如 CLI)使用。
const { t } = useTranslator(...); const { t } = await getTranslator(...);
在部分 request-scoped 的 server 執行環境中,Translator 可能會被綁定至執行上下文,供後續處理使用。
Methods
t()
解析翻譯 key,並回傳對應的翻譯值。
第二個參數可提供插值資料(interpolation)。
// messages: { en: { hello: "Hello, {name}" } } t("hello"); // → "Hello, {name}" t("hello", { name: "Intor" }); // → "Hello, Intor"
tRich()
解析翻譯 key,並保留其語意結構,回傳可組合的結果。
第二個參數用於定義結構映射,第三個參數用於提供插值資料。
// ――― Returns ReactNode ――― // messages: { en: { hello: "Hello, <link>{name}</link>" } } tRich("hello"); // → Hello, <link>{name}</link> tRich("hello", { link: (children) => <a href="/">{children}</a> }, { name: "Intor" }); // → Hello, <a href="/">Intor</a>// ――― Returns VNode children ――― // messages: { en: { hello: "Hello, <link>{name}</link>" } } tRich("hello"); // → ["Hello, ", VNode] tRich("hello", { link: (children) => h("a", { href: "/" }, children) }, { name: "Intor" }); // → ["Hello, ", VNode]// ――― Returns HTML string ――― // messages: { en: { hello: "Hello, <link>{name}</link>" } } {@html $tRich("hello")} // → 'Hello, <link>{name}</link>' {@html $tRich("hello", { link: (children) => `<a href="/">${children}</a>` }, { name: "Intor" })} // → 'Hello, <a href="/">Intor</a>'// ――― Returns HTML string ――― // messages: { en: { hello: "Hello, <link>{name}</link>" } } tRich("hello") // → 'Hello, <link>{name}</link>' tRich("hello", { link: (children) => `<a href="/">${children}</a>` }, { name: "Intor" }) // → 'Hello, <a href="/">Intor</a>'
Note
tRich()會保留翻譯內容的結構,請確保翻譯內容與相關資料皆可信。
hasKey()
檢查指定的翻譯 key 是否存在。
預設以目前語系為準,亦可指定目標語系進行檢查。
// messages: { en: { hello: "Hello" }, fr: {} } hasKey("hello"); // → true hasKey("hello", "fr"); // → false
setLocale()
僅於
useTranslator中提供
切換目前的語系。
setLocale("en")