Tintin81
Tintin81

Reputation: 10215

How to iterate over nested YML file without having to specify node names?

In my Rails app I have this YAML file for localization purposes:

en:

  benefits:

    b01:
      heading: "Vestibulum viverra"
      text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."

    b02:
      heading: "Nulla sed mollis massa"
      text: "Suspendisse potenti. Vestibulum viverra, lorem ac tincidunt tempor, elit eros ornare nisl."

    b03:
      heading: "Lorem ipsum dolor"
      text: "Nulla sed mollis massa, in efficitur est. Nunc ex risus, rutrum ut mi non, mollis pulvinar nisl."

In my view I do something like this:

<% (1..3).each do |n| %>
    <% number = sprintf('%02d', n) %>
    <h2><%= raw t("benefits.b#{number}.heading") %></h2>
    <p><%= raw t("benefits.b#{number}.text") %></p>
<% end %>

Is there a way to achieve the same thing without having to specify the number of the last YAML node ("3") in an each loop?

Thanks for any help.

Upvotes: 1

Views: 402

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You dont need numbers or indexes, just iterate over the keys, here is an example:

<% I18n.t('benefits').keys.each do |k| %>
  <%= I18n.t("benefits.#{k}.heading") %>
  <%= I18n.t("benefits.#{k}.text") %>
<% end %>

Because I18n.t("benefits") returns a hash, we can use the keys method on it. No matter how many keys are in the file.

Upvotes: 1

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33471

As a hash object, you can access each value and there the heading and text keys:

<% I18n.t('benefits').each_value do |value| %>
  <%= value[:heading] %><br>
  <%= value[:text] %><br>
<% end %>

Upvotes: 3

Related Questions