"國際化"
多國語言是一個國際型必備的要素,來看看 Rails 如何做多國語言吧
這邊我們想要有 英文版 和 繁體中文版 兩種
首先,做好詞彙表
config/locales/en.yml
en:
hello: "Hello world"
index: "Index Page of Girb"
button:
new: "New"
placeholder:
search_name: "Search Name"
config/locales/zh_tw.yml
zh-TW:
hello: "哈囉"
index: "個首頁"
button:
new: "新增"
placeholder:
search_name: "名字搜尋"
到 application_controller.rb 修改程式碼如下:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
before_filter :set_locale
protect_from_forgery with: :exception
def set_locale
if params[:locale] && I18n.available_locales.include?( params[:locale].to_sym )
session[:locale] = params[:locale]
end
I18n.locale = session[:locale] || I18n.default_locale
end
end
接下來去 views 把想換成多國語言的地方給置換掉
app/views/girbs/index.html.erb
<div class="container">
<h1><%= t('index') %> ( <%= @girbs.count %> )
<% if @girbs.count != Girb.all.count %>( Filter: <%= @girbs.first.level %> ) <% end %></h1>
<%= will_paginate @products %>
<span class="pull-right">
.
.
.
<%= form_tag(girbs_path, method: :get, id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: t('placeholder.search_name') %>
<%= submit_tag "Search", name: nil %>
<% end %>
app/views/layouts/application.html.erb
<!-- start of footer -->
<div class = "navbar navbar-default navbar-fixed-bottom">
<div class = "container">
<sapn class = "navbar-text">Site Built By Hazetodo </span>
<%= link_to "Bilink", girbs_path, :class => "navbar-btn btn-danger btn btn-sm" %>
<%= link_to new_girb_path, :class => "navbar-btn btn btn-primary btn-sm " do %>
<i class=" fa fa-plus fa-sm"></i> <%= t 'button.new' %>
<% end %>
<%= link_to raw('<i class="fa fa-plus fa-sm"></i> New'), new_girb_path, :class => "navbar-btn btn btn-warning btn-sm" %>
</div>
</div>
<!-- end of footer -->