0

给定以下 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>

知道这个特定的例子不起作用。我只是想举例说明我想要做什么。这是一个不好的做法吗?如果是这样,您将如何处理它?

4

3 回答 3

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"
于 2013-09-18T13:36:26.777 回答
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
于 2013-09-18T04:29:54.487 回答
0

在 yml 中使用哈希

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

像你的第二个例子一样

<% data.product_types.products.each do |product_type, product_url|  %>
  <li><a href="<%= product_url %>"><%= product_type %></a></li>
<% end %>
于 2013-09-18T04:58:47.770 回答