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; 
}