2010-08-13 12 views
0

현재 저는 다른 언어로 번역되고있는 작은 웹 사이트를 만들고 있습니다. Rails의 out-of-the-box 번역본 인 l18n을 사용합니다. 현지화를 변경하려면 locale이라는 매개 변수를 지정해야합니다 (예 : http://localhost:3000/?locale=nl).현지화가 있는지 확인하는 방법은 무엇입니까?

ApplicationController에서이 매개 변수는 세션 변수에 저장되고 현지화로 사용됩니다. 로케일이 실제로 존재하는지 어떻게 확인할 수 있습니까? 내장 함수가 있습니까? 아니면 확인을 위해 모든 현지화 파일에 exists: "true"을 추가해야합니까?

답변

1

로켈이없는 경우 레일스는 기본 로켈로 "en"이 기본 설정됩니다. 따라서 http://localhost:3000/?locale=de을 전달하면 해당 번역이 존재하지 않으므로 역겨워하려면 'en'이 사용됩니다.

여기 봐 http://guides.rubyonrails.org/i18n.html, 특히 "절 2.3 설정 및 로케일을 전달"가

#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}" 

그러면와 ApplicationController에 쉽게 액세스 할 수 있도록 일정하게 포장 할 수 있습니다

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

당신은 구현할 수를 그것은 당신의 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

관련 문제