【问题标题】:Is it possible to use interpolation in YAML translation keys?是否可以在 YAML 翻译键中使用插值?
【发布时间】:2014-07-04 08:55:40
【问题描述】:

假设我在一个 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}')}"

【问题讨论】:

    标签: ruby-on-rails internationalization yaml interpolation


    【解决方案1】:

    是的,它有效,除了要应用插值外,您需要使用双引号,而不是单引号:

    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"
    

    【讨论】:

    • 嗯,就是这样 - 我想在 YAML 键中使用插值,而不是 YAML 值。
    • 说实话,我之前没有尝试过,我几乎可以肯定,#{} 中的#{} 不起作用。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多