how to use rails i18n fallback features

后端 未结 6 1646
难免孤独
难免孤独 2020-12-03 13:02

I have this i18n problem

activerecord:
  notices:
    messages:
      success: 
        create: \"Something was created\"
    models:
      user:
        suc         


        
6条回答
  •  甜味超标
    2020-12-03 13:56

    There is a misunderstanding with the I18n Fallback feature.

    This feature causes that when there is a missing translation exception (in this case, it happens when I18n fails to find the value associated with the "activerecord.notices.models.book.success.create" key in the locale files of your current language) I18n will lookup in the predefined list of fallbacks languages the value of the key that generated the missing translation exception, if it's found I18n will returned that value, but if it's not found in any of those other locale files I18n will return the missing translation exception.

    So when you defined config.i18n.fallbacks = true, that doesn't mean that when a missing translation exception occurs, in this case:

    I18n.t("activerecord.models.book.success.create")
    # => "translation missing: de, activerecord, notices, models, book, success, create"
    

    I18n will lookup a similar key in your locale files to return his value, could be:

    I18n.t("activerecord.models.user.success.create")
    # => "Thanks for registration"
    

    What will happens it's that I18n will lookup in yours defaults fallback languages for the specific language where the missing translation exception has occurred.


    A good example of usage will be:

    # using :"en-US" as a default locale:
    I18n.default_locale = :"en-US" 
    I18n.fallbacks[:es] # => [:es, :"en-US", :en]
    

    Locales files:

    es:
      activerecord:
        notices:
          messages:
            success: 
              create: "Algo fue creado"
          models:
            user:
              success:
                create: "Gracias por registrarte"
    
    en-US:
      activerecord:
          ...
          models:
            books:
              success:
                create: "The model was created" 
    

    Call in English site:

    I18n.t("activerecord.models.books.success.create")
    # => "The model was created"
    

    Call in Spanish site:

    #with config.i18n.fallbacks = false
    I18n.t("activerecord.models.books.success.create")
    # => "translation missing: es, activerecord, models, book, success, create"
    
    #with config.i18n.fallbacks = true
    I18n.t("activerecord.models.books.success.create")
    # => "The model was created"
    

    For more information check: https://github.com/ruby-i18n/i18n

提交回复
热议问题