2015-04-22 11 views
6

Jak mogę wyświetlić elementy w moim yml i przeglądać je w widoku i uzyskiwać dostęp do ich właściwości? Mój obecny kod otrzymuje tylko ostatni element z listy. Chcę przejrzeć w widoku listę elementów i wyświetlić ich elementy title i description.Szyny i18n lista elementów i zapętlenie w widoku

np.

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" 

widok:

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

Wynik:

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

pożądany rezultat:

first item 
    a random description 

    second item 
    another item description 

Odpowiedz

8

Użyj tego zamiast:

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

Również lista elementów nie jest określona prawidłowo:

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

użyć następującej składni, aby zdefiniować tablicę w YAML:

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

Aby to sprawdzić możesz zrobić w konsoli 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

Tak! Tak było. Świetnie. Musiałem dodać ".each", aby poprawnie się zapętlił. – DogEatDog