firedev
firedev

Reputation: 21088

Disable translation_missing for english only in Rails

Is there a way to prevent .translation_missing class from appearing in views if the language is english? Since the english text is correct I don't need to translate it.

Right now I added styles to mask span.translation_missing if the locale is default span, but I'd rather want it to not appear at all if the locale is :en

Update: Just to be clear, I do translations in .erb files, so say <%= t "Menu item" %> becomes <span class="translation_missing">Menu item<span> which is overkill. I just need it to leave the original string alone for :en locale

Upvotes: 2

Views: 1172

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

I don't think there is a way to do this through the standard methods, but you could just add a patch like this:

module I18n::MissingTranslation::Base

  def html_message_with_en_fix
    (locale == :en) ? key : html_message_without_en_fix
  end
  alias_method_chain :html_message, :en_fix

  def message_with_en_fix
    (locale == :en) ? key : message_without_en_fix
  end
  alias_method_chain :message, :en_fix

end

Alternatively, if you don't want to use a patch, you can also define your own method and catch the exception yourself:

def my_translate(key)
  begin
    I18n.t(key, :raise => I18n::MissingTranslationData)
  rescue I18n::MissingTranslationData
    (I18n.locale == :en) ? key.to_s : I18n.t(key)
  end
end

See also this answer.

(I've updated both answers to return the translation string rather thank blank/nil.)

Upvotes: 2

Related Questions