config --> locales --> 下面有 en.yml, zh-CN.yml
默认中文,config --> application.rb 配置如下
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb, yml}').to_s]
config.i18n.default_locale = :"zh-CN"
config.i18n.available_locales = ['en', 'zh-CN']
config.i18n.fallbacks = true
config.encoding = 'utf-8'
views
<li class="dropdown1" id="language" >
<a id="dropdown-toggle1" href="#">
<% if cookies[:user_locale] == 'zh-CN' %>
<%= image_tag 'language/zh-CN.png',class:'lang-icon' %><b class="caret"></b>
<% elsif cookies[:user_locale] == 'en' %>
<%= image_tag 'language/us-min.png',class:'lang-icon' %><b class="caret"></b>
<% elsif cookies[:user_locale] == 'hk-CN' %>
<%= image_tag 'language/hk-CN.png',class:'lang-icon' %><b class="caret"></b>
<% end %>
</a>
<ul class="dropdown-menu1" id='homeland'>
<li><a href="/language/?locale=zh-CN" id='cn'><%#= image_tag 'language/zh-CN.png',class:'lang-icon' %></a></li>
<li><a href="/language/?locale=hk-CN" id='cn'><%= image_tag 'language/hk-CN.png',class:'lang-icon' %></a></li>
<li><a href="/language/?locale=en" id='us'><%= image_tag 'language/us-min.png',class:'lang-icon' %></a></li>
</ul>
</li>
控制器application_controller.rb
before_action :set_locale
def set_locale
cookies[:user_locale] = 'zh-CN' if cookies[:user_locale].blank?
if cookies[:user_locale] && I18n.available_locales.include?(cookies[:user_locale].to_sym)
@locale = cookies[:user_locale].to_sym
else
@locale = http_accept_language.compatible_language_from(I18n.available_locales)
cookies.permanent[:user_locale] =@locale
end
I18n.locale =@locale || I18n.locale
end
控制器home_controller.rb
def language
@locale = params[:locale].to_s.strip.to_sym
@locale = I18n.default_locale unless I18n.available_locales.include?(@locale)
cookies.permanent[:user_locale] = @locale
if request.env["HTTP_REFERER"].PRESENT?
redirect_to '/'
else
redirect_to '/'
end
end