0

我使用的是I18n(簡單後端)內置的Rails。我已將默認區域設置爲:en並啓用了回退。比方說,我有英文和西班牙文的特定項目翻譯。現在德國的一位訪問者來到我的網站,它回落到英語。我將如何去檢測這個後備並將其包裝在一個跨度中?Rails I18n放在翻譯文本週圍如果使用後備

<span class="fallback">Hello</span>,而不是僅僅Hello

這樣,那麼我可以使用客戶端的機器翻譯。

我希望避免寫我自己的後端來取代「簡單」。

回答

0

不得不求助於壓倒一切的翻譯功能的I18n ::後端::回退 https://github.com/svenfuchs/i18n/blob/master/lib/i18n/backend/fallbacks.rb

module I18n 
    module Backend 
    module Fallbacks 
     def translate(locale, key, options = {}) 
     return super if options[:fallback] 
     default = extract_non_symbol_default!(options) if options[:default] 

     options[:fallback] = true 
     I18n.fallbacks[locale].each do |fallback| 
      catch(:exception) do 
      result = super(fallback, key, options) 
      if locale != fallback 
       return "<span class=\"translation_fallback\">#{result}</span>".html_safe unless result.nil? 
      else 
       return result unless result.nil? 
      end 
      end 
     end 
     options.delete(:fallback) 

     return super(locale, nil, options.merge(:default => default)) if default 
     throw(:exception, I18n::MissingTranslation.new(locale, key, options)) 
     end 
    end 
    end 
end 

我只是把這個代碼在初始化。

這讓我感覺非常混亂......我仍然喜歡將其他人的更好答案標記爲正確。

0

更好的解決方案,使用I18n中的元數據模塊。還登錄一個私人日誌文件,以幫助發現缺失的翻譯。您可以使用Rails.logger替換這些調用或將其刪除。

I18n::Backend::Simple.include(I18n::Backend::Metadata) 

# This work with <%= t %>,but not with <%= I18n.t %> 
module ActionView 
    module Helpers 
    module TranslationHelper 
     alias_method :translate_basic, :translate 
     mattr_accessor :i18n_logger 

     def translate(key, options = {}) 
     @i18n_logger ||= Logger.new("#{Rails.root}/log/I18n.log") 
     @i18n_logger.info "Translate key '#{key}' with options #{options.inspect}" 
     options.merge!(:rescue_format => :html) unless options.key?(:rescue_format) 
     options.merge!(:locale => I18n.locale) unless options.key?(:locale) 
     reqested_locale = options[:locale].to_sym 
     s = translate_basic(key, options) 
     if s.translation_metadata[:locale] != reqested_locale && 
      options[:rescue_format] == :html && Rails.env.development? 

      @i18n_logger.error "* Translate missing for key '#{key}' with options #{options.inspect}" 
      missing_key = I18n.normalize_keys(reqested_locale, key, options[:scope]) 
      @i18n_logger.error "* Add key #{missing_key.join(".")}\n" 

      %(<span class="translation_fallback" title="translation fallback #{reqested_locale}->#{s.translation_metadata[:locale]} for '#{key}'">#{s}</span>).html_safe 
     else 
      s 
     end 
     end 
     alias :t :translate 

    end 
    end 
end 

然後用CSS樣式

.translation_fallback { 
    background-color: yellow; 
} 

.translation_missing { 
    background-color: red; 
}