Interpolation in I18n array

吃可爱长大的小学妹 提交于 2019-12-20 14:36:02

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/21574900/interpolation-in-i18n-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!