2015-04-22 12 views
6

Làm cách nào để liệt kê các phần tử trong số yml và lặp qua các phần tử đó trong chế độ xem và truy cập các thuộc tính của chúng? Mã hiện tại của tôi chỉ nhận được mục cuối cùng trong danh sách. Tôi muốn lặp qua trong danh sách các mục và hiển thị các phần tử titledescription của chúng.Danh sách các mục và vòng lặp Rails i18n trong dạng xem

ví dụ:

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" 

xem:

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

Kết quả:

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

mong muốn Kết quả:

first item 
    a random description 

    second item 
    another item description 

Trả lời

8

Sử dụng này để thay thế:

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

Ngoài ra, danh sách các mục của bạn không được định nghĩa đúng:

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

Sử dụng cú pháp sau đây để xác định một mảng trong YAML:

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

Để kiểm tra điều này , bạn có thể thực hiện trong bảng điều khiển IRB của mình:

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

Có! Điều đó đã làm điều đó. Ran tuyệt vời. Tôi đã phải thêm một '.each' cho nó để lặp lại đúng cách. – DogEatDog

Các vấn đề liên quan