Search code examples
ruby-on-railsinternationalizationerbrails-i18n

Rails i18n use array


I got a situation, there are many kinds of receipt in my project. I store them in integer.

In i18n file, I declare translation in this way.

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

However, it's not convenient for me. In view, I need to write if, else syntax to choose which term I need. Like this.

<% 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>
...

Is there a way I can use array to declare? Like

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

Or is there a better way I can use?


Solution

  • The :"..." symbol syntax allows string interpolation just like double quoted strings so you can say things like:

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

    Also, the t helper eventually calls I18n.translate and 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'
    

    so you can skip the symbols and just use strings:

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