ITeye博客

Rails实现多国语言版-gettext

taito · 2008-05-21 11:02 · ROR中级班 · 编程语言 · Markdown

安装gettext,可以下载gem包或者在线安装。

gem install gettext

完成后配置你的项目:

a. 在application.rb加入

require 'gettext/rails'   # 这句一定要加
    
def cookie_lang(my_lang)		
   cookies["lang"] = my_lang
end

b. 在Rakefile文件增加包含文件并增加两个任务

 require 'gettext/utils'

desc "Update pot/po files to match new version." 
task :updatepo do
   MY_APP_TEXT_DOMAIN = "taito" 
   MY_APP_VERSION     = "taito 0.0.1"    
   GetText::ActiveRecordParser.init(:activerecord_classes=>['activerecord::base'])
   GetText.update_pofiles(MY_APP_TEXT_DOMAIN, 
   Dir.glob("{app,lib}/**/*.{rb,rhtml,rjs,rxml}"), 
      MY_APP_VERSION)
   end

   desc "Create mo-files for L10n" 
     task :makemo do
     GetText.create_mofiles(true, "po", "locale")
   end

c.在enviornment.rb 中加入

require 'gettext/rails'

d.在根目录下建立po目录,并增加几种语言目录 en , zh, jp等。 po |- en |- zh |- jp

e.如果是在windows下安装,可能还要装一个二进制版本的gettext 下载地址:http://download.csdn.net/source/461970 如果不装可能会出现如下情况:

No such file or directory - msgmerge po/xx.pot tmp.pot

装好后,在windows下配好相应bin目录的path。(包括gem的gettext/bin也要配好)

f.在根目录下运行rake updatepo 在项目的po目录下会生成pot文件。将这个文件改名为po后,拷贝到en ,zh ,jp 下。

g.在根目录下运行rake makemo 这个命令会自动在 locale 下创建对应的语言版本以及 .mo 文件,翻译工作完成

h.在要显示多语言的地方 如.rb文件,.rhtml文件用_('square') ,来表示,每加一个这样的符号。在rake updatepo时会自动对应出相关文件。

j.切换语言的方法即是改变cookie 如:

Views:
<%=link_to _('Chinese'), :controller=>'/admins', :action=>'select_lang',:lang=>'zh' %>
<%=link_to _('English'), :controller=>'/admins', :action=>'select_lang',:lang=>'en' %>
    
  Controller:  # 例子,根据自己的需要改变
  def select_lang   
     lang = params[:lang]
     lang = 'zh' unless lang =~ /(en)|(zh)|(jp)/
     cookies['lang'] = lang
     redirect_to home_path
  end

k.其它 如果要显示带参数方法,可以用如下方法:

_("%{filename} was not found") % {:filename => "foo.rb"}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。