如果使用回退,Rails I18n会在翻译文本周围放置span



我使用的是内置在I18n(简单后端)的Rails。我将缺省区域设置设置为:en并启用了回退。假设我有一个特定项目的英语和西班牙语翻译。现在,一个德国访问者来到我的网站,它又回到了英语。我该如何检测回退并将其包裹在跨度中呢?

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

这样我就可以使用客户端机器翻译了。

我希望避免编写自己的后端来取代"Simple"。

不得不在I18n::Backend::FallBacks中重写翻译函数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

我只是把这段代码放在了一个初始化式中。

我觉得很乱…我还是愿意把别人更好的答案标记为正确的。

一个更好的解决方案,使用来自I18n的元数据模块。还记录在一个私人日志文件中,以帮助发现缺失的翻译。您可以用Rails替换这些调用。

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

最新更新