开发者

How to check if a localization exists?

I am creating a little website which is currently being translated into differen开发者_如何学JAVAt languages. I use Rails' out-of-the-box translation: l18n. To change the localization, a parameter called locale must be given, e.g.: http://localhost:3000/?locale=nl.

In ApplicationController this parameter is saved into a session variable and used as localization. How can I check if the locale actually exists? Are there any built in functions, or do I need to add an exists: "true" to every localization file to check it?


Rails will default to "en" as the default locale in case if a locale doesn't exist. So to be nasty if I pass http://localhost:3000/?locale=de and that translation doesn't exist, 'en' will be used.

Have a look here http://guides.rubyonrails.org/i18n.html , especially the section "2.3 Setting and Passing the Locale"

#config/initializers/available_locales.rb 

# Get loaded locales conveniently 

module I18n 
 class << self  
  def available_locales; backend.available_locales; end  
 end  
 module Backend 
   class Simple 
     def available_locales; translations.keys.collect { |l| l.to_s }.sort; end  
   end  
 end 
end 

# You need to "force-initialize" loaded locales 
I18n.backend.send(:init_translations) 

AVAILABLE_LOCALES = I18n.backend.available_locales 
RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}" 

You can then wrap the constant for easy access in ApplicationController:

class ApplicationController < ActionController::Base 
  def available_locales; AVAILABLE_LOCALES; end 
end 

You can implement it like this in your ApplicationController:

before_filter :set_locale 

def set_locale 
  I18n.locale = extract_locale_from_params 
end 

def extract_locale_from_params 
  parsed_locale = params[:locale] 
 (available_locales.include? parsed_locale) ? parsed_locale : nil 
end  

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜