/book/list?lang=es
15 國際化
版本 6.2.0
15 國際化
Grails 支援國際化 (i18n),利用基礎的 Spring MVC 國際化支援。使用 Grails,您可以根據使用者的地區設定自訂顯示在檢視中的文字。引用 Locale 類別的 javadoc
Locale 物件代表特定地理、政治或文化區域。需要 Locale 來執行其任務的作業稱為地區設定敏感,並使用 Locale 為使用者量身打造資訊。例如,顯示數字是地區設定敏感的作業,數字應根據使用者原生國家/地區或文化的習慣/慣例進行格式化。
15.1 了解訊息組
現在您對地區設定有所了解,要在 Grails 中使用它們,請建立包含您希望呈現的不同語言的訊息組檔案。Grails 中的訊息組位於 grails-app/i18n
目錄中,而且是單純的 Java 屬性檔案。
依慣例,每個組開頭為 messages
,結尾為地區設定。Grails 在 grails-app/i18n
目錄中提供多種語言的數個訊息組。例如
-
messages.properties
-
messages_da.properties
-
messages_de.properties
-
messages_es.properties
-
messages_fr.properties
-
…
預設情況下,除非使用者已指定區域設定,否則 Grails 會在 messages.properties
中尋找訊息。你可以透過建立一個新的屬性檔來建立自己的訊息套件,該屬性檔的結尾為你感興趣的區域設定。例如,英國英語的 messages_en_GB.properties
。
15.2 變更區域設定
預設情況下,使用者區域設定會從輸入的 Accept-Language
標頭偵測。你可以透過將稱為 lang
的參數傳遞給 Grails 作為要求參數,來提供使用者切換區域設定的功能
Grails 會自動切換使用者的區域設定,後續要求會使用已切換的區域設定。
預設情況下,Grails 使用 SessionLocaleResolver 作為 localeResolver
bean。
你可以輕鬆變更預設區域設定
import org.springframework.web.servlet.i18n.SessionLocaleResolver
beans = {
localeResolver(SessionLocaleResolver) {
defaultLocale= new Locale('es')
}
}
其他 localeResolver
可用。例如,你可以將已切換的區域設定儲存在 Cookie 中
import org.springframework.web.servlet.i18n.CookieLocaleResolver
beans = {
localeResolver(CookieLocaleResolver) {
defaultLocale= new Locale('es')
}
}
或修正區域設定
import org.springframework.web.servlet.i18n.FixedLocaleResolver
beans = {
localeResolver(FixedLocaleResolver, new Locale('de'))
}
15.3 讀取訊息
在檢視中讀取訊息
你需要訊息最常見的地方是在檢視中。請使用 message 標籤
<g:message code="my.localized.content" />
只要你在 messages.properties
中有一個鍵(加上適當的區域設定字尾),例如以下鍵,Grails 就會查詢訊息
my.localized.content=Hola, me llamo John. Hoy es domingo.
訊息也可以包含參數,例如
<g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />
訊息宣告指定動態指定的定位參數
my.localized.content=Hola, me llamo {0}. Hoy es {1}.
使用 MessageSource 在 Grails 工件中讀取訊息
在 Grails 工件中,你可以注入 messageSource
,並使用 getMessage
方法加上參數:訊息代碼、訊息參數、預設訊息和區域設定來擷取訊息。
import org.springframework.context.MessageSource
import org.springframework.context.i18n.LocaleContextHolder
class MyappController {
MessageSource messageSource
def show() {
def msg = messageSource.getMessage('my.localized.content', ['Juan', 'lunes'] as Object[], 'Default Message', LocaleContextHolder.locale)
}
使用訊息標籤在控制器和標籤庫中讀取訊息
此外,你可以使用 訊息標籤 在控制器和標籤庫中讀取訊息。但是,使用訊息標籤依賴於 GSP 支援,而 Grails 應用程式不一定有這種支援;例如,REST 應用程式。
在控制器中,你可以呼叫標籤作為方法。
def show() {
def msg = message(code: "my.localized.content", args: ['Juan', 'lunes'])
}
def myTag = { attrs, body ->
def msg = g.message(code: "my.localized.content", args: ['Juan', 'lunes'])
}
15.4 腳手架和 i18n
腳手架包含特定於區域設定的標籤,用於網域類別和網域欄位。例如,如果您有一個具有 title
欄位的 Book
網域類別
class Book {
String title
}
腳手架將使用具有下列金鑰的標籤
book.label = Libro
book.title.label = Título del libro
您可以使用這個屬性模式,也可以想出自己的模式。除了它是腳手架使用的慣例之外,金鑰中使用 label
這個字並無特別用意。