开发者

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

For example:

I18n.t('something')

should outpu开发者_开发技巧t 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


side-note: this might help figuring out what Rails thinks the current scope is (e.g. 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜