我遇到了一个情况,我的项目中有很多种收据。我将它们存储在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]") %>
或者我有更好的方法可以使用吗?
答案 0 :(得分:0)
:"..."
符号语法允许字符串插值,就像双引号字符串一样,所以你可以这样说:
<p><%= t(:"receipt.Receipt.receipt_choice#{receipt.type}") %></p>
<p><%= t(:"receipt.Receipt.choise_detail#{receipt.type}") %></p>
此外,t
助手最终会调用I18n.translate
和that 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>