This is actually a pretty common question, but the short answer is no, this isn't possible unfortunately :(
Use another I18n key in an I18n interpolation
-
15-01-2022 - |
Question
This might be I18n-ception but lets say I have an en.yml
file as below
en:
my_var: Foo
my_message: "This is a message where I'd like to interpolate I18n's %{my_var}"
Is there a way to indicate to I18n that %{my_var}
should be the my_var
key in en.yml
?
I know I could accomplish it by doing something like
I18n.t 'my_message', :my_var => I18n.t('my_var')
but I was hoping I18n has a way to self reference keys.
Solution
OTHER TIPS
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]}") ) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow