使用Gettext实现rails中的多语言版教程

2010-04-02, Posted in Ruby | 2 回复


Gettext 用于系统的国际化(I18N)和本地化(L10N),可以在编译程序的时候使用本国语言支持(Native Language Support(NLS)),其可以使程序的输出使用用户设置的语言而不是英文.安装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,html.erb,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

本文章转摘:http://taito.javaeye.com/blog/195148

标签: , ,

相关日志

2 Comments for this entry

你也讲两句吧~