2

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

firedev
  • 20,898
  • 20
  • 64
  • 94

1 Answers1

2

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.)

Community
  • 1
  • 1
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • Unfortunately produces `ActionView::Template::Error (undefined method `html_safe' for nil:NilClass)` error in production. I was hoping there is a way to do it without patching. – firedev Sep 24 '12 at 07:00
  • Updated my answer so it returns an empty string rather than `nil`. I agree that patching is not the most elegant approach, but it should work. – Chris Salzberg Sep 24 '12 at 07:02
  • Added an alternative approach which doesn't require a patch. See also this answer: http://stackoverflow.com/questions/6027471/how-do-you-rescue-i18nmissingtranslationdata – Chris Salzberg Sep 24 '12 at 07:19
  • Update(1) retuns empty string if translation is missing indeed, but this way all the text in the english version is gone. – firedev Sep 24 '12 at 14:15
  • So you just want to show the key if you're in the English locale? That wasn't very clear. Anyway I updated my answer to do that. – Chris Salzberg Sep 24 '12 at 22:26
  • No worries! Now that I understand what you wanted it makes more sense. – Chris Salzberg Sep 25 '12 at 03:59