给rails系统加i18n,根据浏览器的头去识别用户语言。记录一下相关实现:

1.添加i18n配置

1
2
3
4
# config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.available_locales = [:en, :cn]
config.i18n.default_locale = :cn

2.获取语言设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# app/controller/application_controller.rb
before_action :set_locale
# set local {{{
def set_locale
I18n.locale = get_locale
end
# }}}

# locale {{{
def get_locale
locale = I18n.default_locale

if params[:locale]
locale = params[:locale].downcase
elsif cookies[:locale]
locale = cookies[:locale]
elsif locale = get_accept_language
locale
end
# set cookies
if cookies[:locale] != locale
cookies[:locale] = locale
end

locale
end

def get_accept_language
begin
first_lang = request.env['HTTP_ACCEPT_LANGUAGE'].split(';').first
default_lang = first_lang[0,2].downcase

if default_lang == 'zh'
first_lang[3,2].downcase
else
default_lang
end
rescue
nil
end
end
# }}}

说明:locale的值优先从url地址读取,次之从cookie,最后从浏览器头判断。英文浏览器的头为Accept-Language:en-US,en;,取en即前两位。中文浏览器头为Accept-Language:zh-CN,zh;,取cn即3-5位,转为小写。

3.编辑语言文件

1
2
3
4
5
6
# config/locales/en.yml
en:
hello: "Hello world"
# config/locales/cn.yml
cn:
hello: "你好"
  1. 在模板文件中应用
1
2
3
4
5
6
7
# app/views/home/index.html.erb
<p><%= t('hello'); %></p>
<ul>
<% I18n.available_locales.each.each do |locale| %>
<li><%= link_to locale, params.merge(locale: locale) %></li>
<% end %>
</ul>

说明:点击生成的链接可以手动切换语言,测试的时候方便一些。