是否可以在YAML翻译键中使用插值?

时间:2014-07-04 08:55:40

标签: ruby-on-rails internationalization yaml interpolation

说我在I18n文件中有两个yaml键:

level1:
  level2:
    foo: 'Something'
    bar: 'Something else'

我会像这样引用这些键:t('level1.level2.foo')t('level1.level2.bar')。如果我有变量var,其类型返回'foo''bar',我可以执行以下操作:t('level1.level2.#{var.type}')。现在是更棘手的部分 - 如果我已经使用字符串插值中的键,如下所示:

"The type of the #{var.to_s} variable is #{t('level1.level2.#{var.type}')}"

1 个答案:

答案 0 :(得分:2)

是的,它适用,除了要应用的插值,你需要使用双引号,而不是单引号:

t("level1.level2.#{var.type}")
"The type of the #{var.to_s} variable is #{t("level1.level2.#{var.type}")}"

示例:

[1] pry(main)> var = OpenStruct.new
=> #<OpenStruct>
[2] pry(main)> var.type = 'foo'
=> "foo"
[3] pry(main)> "The type of the #{var.to_s} variable is #{I18n.t("level1.level2.#{var.type}")}"
=> "The type of the #<OpenStruct type=\"foo\"> variable is translation missing: en.level1.level2.foo"