Rails I18n, check if translation exists?
Solution 1
Based on what you've described, this should work:
I18n.t("some_translation.key", :default => "fallback text")
See the documentation for details.
Solution 2
You can also use
I18n.exists?(key, locale)
I18n.exists?('do_i_exist', :en)
Solution 3
:default
is not always a solution. Use this for more advanced cases:
helpers/application.rb:
def i18n_set? key
I18n.t key, :raise => true rescue false
end
any ERB template:
<% if i18n_set? "home.#{name}.quote" %>
<div class="quote">
<blockquote><%= t "home.#{name}.quote" %></blockquote>
<cite><%= t "home.#{name}.cite" %></cite>
</div>
<% end %>
Solution 4
What about this ?
I18n.t('some_translation.key', :default => '').empty?
I just think it feels better, more like there is no translation
Caveat: doesn't work if you intentionally have an empty string as translation value.
Solution 5
use :default param:
I18n.t("some_translation.key", :default => 'some text')
Related videos on Youtube
Comments
-
agmcleod over 3 years
Working on a rails 3 app where I want to check if a translation exists before outputting it, and if it doesn't exist fall back to some static text. I could do something like:
if I18n.t("some_translation.key").to_s.index("translation missing")
But I feel like there should be a better way than that. What if rails in the future changes the "translation missing" to "translation not found". Or what if for some weird reason the text contains "translation missing". Any ideas?
-
Cristian over 8 yearsThis is actually working. The method is not documented though, just mentioned here: rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/…
-
Robert Travis Pierce about 7 years
I18n.exists?('key')
seems like the core evaluation. I've used it in helper_methods for fallback actions if no key value is set, e.g.title = I18n.exists?('page_title.default') ? t('page_title.default') : "Fallback title..."
-
andoke over 6 yearsOne line :
I18n.t('key.special_value', default: I18n.t('key.default_value'))