Search code examples
ruby-on-railsrails-i18n

Rails i18n list of items and looping in view


How can I list elements in my yml and loop through them in the view and access their properties? My current code only gets the last item in the list. I want to loop through in the view the list of items and display their title and description elements.

e.g.

yml:

en:
  hello: "Hello world"
  front_page:
    index:
      description_section:
        title: "MyTitle"
        items:
          item:
            title: "first item"
            description: "a random description"
          item:
            title: "second item"
            description: "another item description"

view:

      <%= t('front_page.index.description_section.items')do |item| %>
          <%= item.title %>
          <%= item.description %>
      <%end %>

Result:

   {:item=>{:title=>"second item", :description=>"another item description"}} 

Desired Result:

    first item
    a random description

    second item
    another item description

Solution

  • Use this instead:

    <% t('front_page.index.description_section.items').each do |item| %>
    # ^ no equal sign here
      <%= item[:title] %>
         #^^^^ this is a hash
      <%= item[:description] %>
    <% end %>
    

    Also, your items list is not defined properly:

    t('front_page.index.description_section.items.item.title')
    # => returns "second item" because the key `item` has been overwritten
    

    Use the following syntax to define an array in YAML:

    items:
    - title: "first item"
      description: "a random description"
    - title: "second item"
      description: "another item description"
    

    To check this, you can do in your IRB console:

    h = {:items=>[{:title=>"first item", :description=>"desc1"}, {:title=>"second item", :description=>"desc2"}]} 
    puts h.to_yaml
    # => returns
    ---
    :items:
    - :title: first item
      :description: desc1
    - :title: second item
      :description: desc2