天天看點

Rails2.2.2之國際化

1. 建立國際化配置檔案config\initializers\i18n.rb

I18n.default_locale = 'en'

LOCALES_DIRECTORY = "#{RAILS_ROOT}/config/locales/"

LANGUAGES = {
  'English' => 'en',
  "Espa\xc3\xb1ol" => 'es',
  "中文" => 'zh'
}
           

2. 在視圖頁面中添加語言切換下拉框

<% form_tag '', :method => 'GET', :class => 'locale' do %>
		<%= select_tag 'locale', options_for_select(LANGUAGES, I18n.locale),
		:onchange => 'this.form.submit()' %>
		<%= submit_tag 'submit' %>
		<%= javascript_tag "$$('.locale input').each(Element.hide)" %>
	<% end %>
           

顯示效果如下

[img]http://dl.iteye.com/upload/attachment/0079/9116/c2a58f5f-4906-3c08-b6e6-9d9d15835970.jpg[/img]

3.建立三個資源檔案config\locales\en.yml,config\locales\es.yml,config\locales\zh.yml,添加感興趣的需要國際化的文本,例如在zh.yml中添加如下文本。

#START:main
  main:
    title:       "産品目錄"
    button:
      add:       "加入購物車"
#END:main
           

在頁面中顯示代碼

<%= I18n.t 'main.title' %>

<%= I18n.t 'main.botton.add' %>

如此簡單。

[quote]一個跟國際化無關的亂碼問題:有時在頁面中輸入中文儲存到資料庫時是亂碼,這可能是因為資料庫編碼不是UTF-8[/quote]