How to Add Values Dynamically to I18N

How to add values dynamically to I18n?

The dirty way

You could override the load_translation method in I18n::Backend::Base through a custom module or gem or -- cough -- monkey patching -- cough -- to fetch the translations from different sources, it feels dirty to me but I guess you could try experimenting with that before going further.

https://github.com/svenfuchs/i18n/blob/master/lib/i18n/backend/base.rb#L13

Changing the I18n Backend

You can create a different I18n Backend that implements the expected behaviour and hook it up to I18n through an initializer. I'm assuming that's how tools like localeapp and phraseapp do it. There is a method just for that in I18n::Config

https://github.com/svenfuchs/i18n/blob/master/lib/i18n/config.rb#L23

So you can just do this in an initializer

I18n.backend = MyAwesomeI18nBackend.new

The good thing is that you can chain multiple backends together

I18n.backend = I18n::Backend::Chain.new(MyAwesomeI18nBackend.new)

It makes sure you still have access to the default translation backends or other custom backends.

References

Ryan made a great railscast back in the days explaining how to change backends. It's a bit outdated but it gives you a good idea of what needs to be done.

I18n Backends

If your translations are related to some data saved in a database, you could also use globalize to handle those.

https://github.com/globalize/globalize

EDIT: Simpler way by Dima

If you have a hash, you can use the default backend's store_translation method to load translations from that hash.

I18n.backend.store_translations(:en, {test: "YOOOOOHHHHHOOOO"})

How do I set the key of {t('key', {value})} dynamically with react-i18next

Inside the t function you can call that value dynamically with ${item} or [item] as {item} will not work. Hope this was helpful.

rails - how to dynamically add/override wording to i18n yaml

It should not overwrite your "en" locale. Translations are merged. store_translations in the simple I18n backend calls merge_translations, which looks like this:

# Deep merges the given translations hash with the existing translations
# for the given locale
def merge_translations(locale, data)
locale = locale.to_sym
translations[locale] ||= {}
data = deep_symbolize_keys(data)

# deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
translations[locale].merge!(data, &merger)
end

As you can see, only the keys you enter in the latter translation yml file will be overwritten.



Related Topics



Leave a reply



Submit