2015-04-22 23 views
6

如何列出我的yml中的元素並在視圖中遍歷它們並訪問它們的屬性?我目前的代碼只獲取列表中的最後一個項目。我想在視圖中循環顯示項目列表並顯示它們的titledescription元素。Rails i18n項目列表和視圖中的循環

例如

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" 

視圖:

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

結果:

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

所需的結果:

first item 
    a random description 

    second item 
    another item description 

回答

8

用這個代替:

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

此外,您的項目列表不正確定義:

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

使用以下格式在YAML定義數組:

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

要檢查此,你可以在你的IRB控制檯上做:

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 
+0

是的!那樣做了。很好。我不得不添加一個'.each'來正確循環。 – DogEatDog