1. 新建項目并進入目錄
#在沒有修改bundle的sources默認地址時
#新建項目時進行bundle會很慢,可以先直接跳過bundle
rails new blog --skip-bundle
cd blog
#設置bundle默認的sources
#(注:只要設置一次,以后再建項目時,就可以直接bundle了)
bundle config mirror.https://rubygems.org http://gems.ruby-china.org
#bundle
bundle update
bundle install
2.創建一個簡單的頁面
#生成article模塊
rails g scaffold Article name:string title:string content:text
#數據庫遷移
rake db:migrate
3.啟動
#使用默認方式啟動,在瀏覽器中訪問http://localhost:3000/articles
rails server
4.準備本地化文件
下載地址:zh-CN.yml
放到blog/config/locales目錄下
5.修改application.rb
文件在blog目錄下
module Blog
class Application < Rails::Application
+ config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
+ config.i18n.default_locale = :'zh-CN'
+ config.encoding = 'utf-8'
end
end
6.修改application_controller.rb
文件在blog/app/controllers目錄下
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
+ before_action :set_locale
+ def set_locale
+ I18n.locale = params[:locale] || I18n.default_locale
+ end
end
7.修改zh-CN.yml,添加models相關翻譯
我們可以把models理解為app下的models目錄(實際就是與他對應的,同時也是與數據庫的表對應)
---
zh-CN:
activerecord:
// models為模塊名
+ models: #關鍵字,下面是對應的模塊名
+ article: 文章
+ attributes: #關鍵字,下面是對應的表名
+ article: #表名單數格式,下面是對應的字段
+ name: 名稱
+ title: 標題
+ content: 內容
errors:
messages:
record_invalid: "驗證失敗: %{errors}"
restrict_dependent_destroy:
has_one: 由于 %{record} 需要此記錄,所以無法移除記錄
has_many: 由于 %{record} 需要此記錄,所以無法移除記錄
...
這時我們可以在添加、修改頁面看到成果。
new.png
edit.png
8.進一步本地化
我們可以看到index頁面還沒有被本地化
繼續添加本地化文件zh-CN.yml
---
zh-CN:
+ Blog: 博客
+ Name: 名稱
+ Title: 標題
+ Content: 內容
+ Show: 顯示
+ Edit: 修改
+ Destroy: 刪除
+ Articles: 文章
+ New Article: 添加文章
+ Editing Article: 修改文章
+ Are you sure?: 你確定?
+ Edit: 修改
+ Back: 返回
activerecord:
models:
article: 文章
attributes:
article:
name: 名稱
title: 標題
content: 內容
修改views/articles下的erb文件
<p id="notice"><%= notice %></p>
-<h1>Articles</h1>
+<h1><%= t 'Articles'%></h1>
<table>
<thead>
<tr>
- <th>Name</th>
+ <th><%= t 'Name'%></th>
- <th>Title</th>
+ <th><%= t 'Title'%></th>
- <th>Content</th>
+ <th><%= t 'Content'%></th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @articles.each do |article| %>
<tr>
<td><%= article.name %></td>
<td><%= article.title %></td>
<td><%= article.content %></td>
- <td><%= link_to 'Show', article %></td>
+ <td><%= link_to (t 'Show'), article %></td>
- <td><%= link_to 'Edit', edit_article_path(article) %></td>
+ <td><%= link_to (t 'Edit'), edit_article_path(article) %></td>
- <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?'} %></td>
+ <td><%= link_to (t 'Destroy'), article, method: :delete, data: { confirm: (t 'Are you sure?') } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
-<%= link_to 'New Article', new_article_path %>
+<%= link_to (t 'New Article'), new_article_path %>
其它的erb文件做相應的修改即可,修改后的效果如下:
index.png
new.png
edit.png
備注:
1.對views這塊沒有發現更好的解決方案,感覺這樣做很呆,不如索性直接改成中文
2.做了本化之后,如果還要顯示英文,可以在請求后面加locale參數,例如:http://localhost:3000/articles/2/edit?locale=en,顯示的就是en狀態
edit.png
3.如果你有更好的方案,請告訴我,我會再更新