是否可以将子项添加到YML列表中?

时间:2013-09-18 04:04:14

标签: ruby-on-rails ruby yaml middleman

鉴于以下YML格式,是否可以或建议映射URL,以便可以填充和链接导航列表等组件?

可以填充:

products:
  - Wizzy Widgets
  - Doohickeys
  - Thingamabobbers

通过以下ERB呈现(文件为/data/product_types.yml):

<% data.product_types.products.each do |product_type|  %>
<li><a href="#"><%= product_type %></a></li>
<% end %>

输出以下标记

<li><a href="#">Wizzy Widgets</a></li>
<li><a href="#">Doohickeys</a></li>
<li><a href="#">Thingamabobbers</a></li>

但也可以链接

products:
  - Wizzy Widgets:
    - url: "/wizzy-widgets"
  - Doohickeys:
    - url: "/doohickeys"
  - Thingamabobbers
    - url: "/thingamabobbers"

通过ERB如此:

<% data.product_types.products.each do |product_type, product_url|  %>
<li><a href="<%= product_url %>"><%= product_type %></a></li>
<% end %>

以便输出以下标记?

<li><a href="/wizzy-widgets">Wizzy Widgets</a></li>
<li><a href="/doohickeys">Doohickeys</a></li>
<li><a href="/thingamabobbers">Thingamabobbers</a></li>

知道这个特定的例子不起作用。我只是想举例说明我要做的事情。这是一种不好的做法吗?如果是这样,你会怎么做呢?

3 个答案:

答案 0 :(得分:2)

如果您对嵌套YML数据感兴趣,可以这样做:

details:
  - name: "Brady Duncan"
    url: "brady-duncan"
    title: "Secretary of Beer Defense"
    bio: "Has a well rounded set of skills (the right brain) who also aggressively networks and enjoys promoting the brand."
    favorite: "Happy Amber"
  - name: "Jeff Hunt"
    url: "jeff-hunt"
    title: "Beer 'Can'nesseur"
    bio: "Has a very deep understanding of the brewing process and the science behind the 'magic'"
    favorite: "Gnarly Brown"
  - name: "Kenny McNutt"
    url: "kenny-mcnutt"
    title: "The 'Beer'ded Baron"
    bio: "The man with the financial plan who also has a refined pallet for identifying flavors in beer."
    - favorite:
      beer: "Psychopathy"
      music: "Bluegrass"
      movies: "Drama"

答案 1 :(得分:1)

试试这个

require 'yaml'

yml = YAML.load(%{
  products:
    -
      name: Wizzy Widgets
      url: /wizzy-widgets
    -
      name: Doohickeys
      url: /doohickeys
    -
      name: Thingamabobbers
      url: /thingamabobbers
})

yml["products"].each do |product|
  puts %{<li><a href="#{product["url"]}%>">#{product["name"]}</a></li>}
end

答案 2 :(得分:0)

在yml中使用哈希

products:
  Wizzy Widgets:
    /wizzy-widgets
  Doohickeys:
    /doohickeys
  Thingamabobbers:
    /thingamabobbers

erb就像你的第二个例子

<% data.product_types.products.each do |product_type, product_url|  %>
  <li><a href="<%= product_url %>"><%= product_type %></a></li>
<% end %>
相关问题