Rails i18n list of items and looping

How can I list the elements in yml and skip them in the view and access their properties? My current code only gets the last item in the list. I want to view a list of elements in a list and display their title and description elements.

eg.

ut:

 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 
+6
source share
1 answer

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 %> 

In addition, the list of your products is not defined correctly:

 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 verify this, you can do this on the 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 
+8
source

Source: https://habr.com/ru/post/985703/


All Articles