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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With