作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在语言环境文件中使用数组,以便能够在特定于语言环境的各种输出方法(ActionMailer 模板、Prawn 文档、HAML 模板)中生成文本块。它工作得很好,但有时我想将变量传递到这些 I18n 调用中。但是,这不起作用。
假设我的语言环境文件如下所示:
en:
my_array:
- "Line 1"
- "Line 2"
- "Line 3 has a %{variable}"
- "Line 4"
I18n.t('my_array', :variable => 'variable named variable')
的输出如下:
["Line 1", "Line 2", "Line 3 has a variable named variable", "Line 4"]
["Line 1", "Line 2", "Line 3 has a %{variable}", "Line 4"]
最佳答案
我认为 i18n gem 本身不支持这样的事情,但是使用一些元编程魔法是可行的。
在初始值设定项(例如 config/initializers/i18n.rb
)中添加以下内容
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
关于ruby-on-rails - I18n 数组中的插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21574900/
我是一名优秀的程序员,十分优秀!