2015-04-22 27 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