简体   繁体   中英

How to use i18n key as default translation in Rails 3?

For example:

I18n.t('something')

should output only

something

if the translation missing.

It is possible: See section 4.1.2 Defaults at Rails Internationalization (I18n) API .

I18n.t :missing, :default => 'Not here'
# => 'Not here'

On rails 4 you can change the exception handler.

Add the following to config/initializers/i18n.rb :

module I18n
  class MissingTranslationExceptionHandler < ExceptionHandler
    def call(exception, locale, key, options)
      if exception.is_a?(MissingTranslation)
        key
      else
        super
      end
    end
  end
end

I18n.exception_handler = I18n::MissingTranslationExceptionHandler.new

Now on you views you can just do:

<p><%= t "Not translated!" %></p>

Guide on the subject: http://guides.rubyonrails.org/i18n.html#using-different-exception-handlers

David's answer is the right solution to the question, another (more verbose) way to do it is to rescue and return the key:

def translate_nicely(key)
  begin
    I18n.translate!(key)
  rescue
    key
  end
end

side-note: this might help figuring out what Rails thinks the current scope is (eg when using ".something")

http://unixgods.org/~tilo/Rails/which_l10n_strings_is_rails_trying_to_lookup.html

this way you can better avoid having missing translations because of incorrect placing of translations strings in the L10n-file / incorrect keys

nope, not possible. If you use I18 you need to have a file that corresponds to the language otherwise I18n will complain.

Of course you can set the default language in your environment.rb file. Should be near the bottom and you can set this for whatever language you want but in your locales/ folder you will need to have a corresponding yml translation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM