I'm using arrays in a locale file to be able to generate blocks of text in various output methods (ActionMailer templates, Prawn documents, HAML templates) that are locale-specific. It works perfectly, but sometimes I want to pass variables into these I18n calls. However, this doesn't work.
Say my locale file looks like this:
en:
my_array:
- "Line 1"
- "Line 2"
- "Line 3 has a %{variable}"
- "Line 4"
I want the output of I18n.t('my_array', :variable => 'variable named variable')
to be as follows:
["Line 1", "Line 2", "Line 3 has a variable named variable", "Line 4"]
However, the output is:
["Line 1", "Line 2", "Line 3 has a %{variable}", "Line 4"]
Will I have to do the interpolation myself after retrieving the array? Or is there a better way to do this?
I think such thing is not supported natively in i18n gem, but it's doable using some meta-programming magic.
In an initializer (say, config/initializers/i18n.rb
) add the following
I18n.backend.instance_eval do
def interpolate(locale, string, values = {})
if string.is_a?(::Array) && !values.empty?
string.map { |el| super(locale, el, values) }
else
super
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With