【问题标题】:How to iterate over nested YML file without having to specify node names?如何在无需指定节点名称的情况下迭代嵌套的 YML 文件?
【发布时间】:2018-05-27 16:50:20
【问题描述】:

在我的 Rails 应用程序中,我有这个 YAML 文件用于本地化目的:

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."

在我看来,我会这样做:

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

有没有办法在each 循环中不必指定最后一个 YAML 节点的编号(“3”)来实现相同的目标?

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails yaml


    【解决方案1】:

    作为哈希对象,您可以访问每个值以及标题和文本键:

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

    【讨论】:

      【解决方案2】:

      你不需要数字或索引,只需遍历键,这里是一个例子:

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

      因为I18n.t("benefits")返回一个哈希值,我们可以对它使用keys方法。 无论文件中有多少键。

      【讨论】:

        猜你喜欢
        • 2016-01-07
        • 1970-01-01
        • 2011-12-26
        • 1970-01-01
        • 2020-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多