i18n hook 從您專案的 "locales" 目錄 (預設為 config/locales
) 讀取 JSON 格式的翻譯檔案。每個檔案對應一個 語系 (通常是一種語言),您的 Sails 後端將會支援該語系。
這些檔案包含特定於語系的字串 (以 JSON 鍵值對的形式),您可以在視圖、控制器等中使用。檔案名稱應與您支援的語言相符。這允許基於請求標頭自動偵測語言。
以下是一個範例語系檔案 (config/locales/es.json
)
{
"Hello!": "Hola!",
"Hello %s, how are you today?": "¿Hola %s, como estas?"
}
可以在控制器動作和策略中透過 req.i18n()
存取語系,或在視圖中透過 __(key)
或 i18n(key)
函式存取。
<h1> <%= __('Welcome to PencilPals!') %> </h1>
<h2> <%= i18n('Hello %s, how are you today?', 'Pencil Maven') %> </h2>
<p> <%= i18n('That\'s right-- you can use either i18n() or __()') %> </p>
請注意,您的字串檔案中的鍵 (例如 "Hello %s, how are you today?") 是區分大小寫的,並且需要完全匹配。關於這裡的最佳方法,有幾種不同的思路;這實際上取決於誰在編輯字串檔案以及編輯頻率。特別是如果您要手動編輯翻譯,則較簡單的全小寫鍵名可能更易於維護。
例如,這是您可以處理 config/locales/es.json
的另一種方式
{
"hello": "hola",
"howAreYouToday": "cómo estás"
}
這是 config/locales/en.json
{
"hello": "hello",
"howAreYouToday": "how are you today"
}
若要表示巢狀字串,請在鍵中使用 .
。例如,以下是一些應用程式 "編輯個人資料" 頁面的字串
{
"editProfile.heading": "Edit your profile",
"editProfile.username.label": "Username",
"editProfile.username.description": "Choose a new unique username.",
"editProfile.username.placeholder": "callmethep4rtysquid"
}
若要判斷請求目前使用的語系,請使用 req.getLocale()
。
若要覆寫請求的自動偵測語言/本地化偏好設定,請使用 req.setLocale()
,並使用新語系的唯一代碼呼叫它,例如:
// Force the language to German for the remainder of the request:
req.setLocale('de');
// (this will use the strings located in `config/locales/de.json` for translation)
預設情況下,node-i18n 將透過檢查請求的語言標頭來偵測請求的所需語言。語言標頭在您使用者的瀏覽器設定中設定,雖然它們在大多數情況下是正確的,但您可能需要彈性地覆寫此偵測到的語系並提供您自己的語系。若要深入了解您可能實作此功能的一種方式,請查看 此 gist。