Use another I18n key in an I18n interpolation Use another I18n key in an I18n interpolation ruby-on-rails ruby-on-rails

Use another I18n key in an I18n interpolation


This is actually a pretty common question, but the short answer is no, this isn't possible unfortunately :(


Currently I struggle for it... And finally I create a custom yaml type.

in init section.

Psych.add_builtin_type('i18n') { |_type, value|  ->(_key, _options) do    value.gsub(/%\{([\w.]+)\}/) do |match|      key = $1.to_sym      if I18n.exists?(key)        I18n.t(key)      else        match      end    end  end}I18n.reload!

in en.yml

en:  my_var: Foo  my_message: !!i18n "This is a message where I'd like to interpolate I18n's %{my_var}"

!!i18n apply custom builtin type.


As you said, maybe it is not a so straight solution to call twice from the view to the translation

<%= t("my_message", my_var: t("my_var") ) %>

but gives you the flexibility to call with a variable

<%= t("my_message", my_var: t("my_#{$item[:slug]}") ) %>