Rails i18n 使用数组

Rails i18n use array

我遇到一个情况,我的项目里有很多种receipt。我将它们存储在 integer.

i18n文件中,我是这样声明翻译的。

hash[:"Receipt"] = {
    :"receipt_choice1"            => "Rc1",
    :"choise_detail2"             => "Rc_datail1",
    :"receipt_choice2"            => "Rc2",
    :"choise_detail2"             => "Rc_datail2",
    :"receipt_choice2"            => "Rc3",
    :"choise_detail2"             => "Rc_datail3",
  }

但是,这对我来说不方便。在视图中,我需要编写 if, else 语法来选择我需要的术语。像这样。

<% if receipt.type == 1 %>
  <p> <%= t(:"receipt.Receipt.receipt_choice1") </p>
  <p> <%= t(:"receipt.Receipt.choise_detail2") </p>
<% elsif receipt.type == 2 %>
  <p> <%= t(:"receipt.Receipt.receipt_choice1") </p>
  <p> <%= t(:"receipt.Receipt.choise_detail2") </p>
...

有什么方法可以用数组来声明吗?喜欢

<%= t(:"receipt.Receipt[receipt.type]") %>

或者有更好的方法可以使用吗?

:"..." 符号语法允许字符串插值,就像双引号字符串一样,因此您可以这样说:

<p><%= t(:"receipt.Receipt.receipt_choice#{receipt.type}") %></p>
<p><%= t(:"receipt.Receipt.choise_detail#{receipt.type}") %></p>

此外,t 助手最终会调用 I18n.translatethat doesn't care if you give it strings or symbols:

# Key can be either a single key or a dot-separated key (both Strings and Symbols
# work). <em>E.g.</em>, the short format can be looked up using both:
#   I18n.t 'date.formats.short'
#   I18n.t :'date.formats.short'

因此您可以跳过符号而只使用字符串:

<p><%= t("receipt.Receipt.receipt_choice#{receipt.type}") %></p>
<p><%= t("receipt.Receipt.choise_detail#{receipt.type}") %></p>