2015-02-11 51 views
1

有沒有一種方法可以讓Rails自動從關鍵字中推斷英文翻譯?如何讓Rails自動從YAML翻譯鍵名中推斷英文翻譯?

目前我必須明確寫出翻譯,因爲否則它只會在視圖中輸出en, devise.confirmations.new.resend_confirmation_instructions

我現在有在config/locales/en.yml文件中寫入:

en: 
    devise: 
    confirmations: 
     new: 
     resend_confirmation_instructions: "Resend confirmation instructions." 

我想什麼有:

en: 
    devise: 
    confirmations: 
     new: 
     resend_confirmation_instructions: 

和視圖應該只是輸出「重新發送確認指令。」這是從該密鑰直接推斷出來的。

+1

有沒有辦法做到這一點(我知道),因爲這完全反駁了翻譯的點。但是在生產中,如果翻譯缺失,Rails將顯示「重新發送確認說明」 – 2015-02-11 15:25:52

+0

啊,它會在生產中這樣做嗎?我不知道。 順便說一句,從英文翻譯鍵獲取英文文本不完全是一個翻譯。無論如何,當您的代碼庫和翻譯密鑰都是英文的時候,這只是一種避免重複工作的便捷方式。 – Magne 2015-02-11 17:07:27

+0

爲此,您可以配置備用語言。點擊此處查看:http://stackoverflow.com/a/7886246/488195 – dgilperez 2015-02-11 17:13:45

回答

2

你總是可以編寫自己的異常處理程序:

#config/initializers/i18n.rb 

module I18n 
    class MissingTranslationExceptionHandler < ExceptionHandler 
    def call(exception, locale, key, options) 
     if exception.is_a?(MissingTranslation) 
     key.split('.').last.try(:humanize) 
     else 
     super 
     end 
    end 
    end 
end 

I18n.exception_handler = I18n::MissingTranslationExceptionHandler.new 

你可以閱讀更多on the guides