我正在尝试使用 HAML 构建一个简单的嵌套 html 菜单,但我不确定如何使用 correct indentation 插入元素,或者构建嵌套树的一般最佳方法。我希望能够做这样的事情,但要无限深入:
- categories.each_key do |category|
%li.cat-item{:id => "category-#{category}"}
%a{:href => "/category/#{category}", :title => "#{category.titleize}"}
= category.titleize
感觉我应该能够很容易地完成这项工作,而无需借助于在 html 中手动编写标签,但我不是递归的最佳人选。这是我目前想出的代码:
查看助手
def menu_tag_builder(array, &block)
return "" if array.nil?
result = "<ul>\n"
array.each do |node|
result += "<li"
attributes = {}
if block_given?
text = yield(attributes, node)
else
text = node["title"]
end
attributes.each { |k,v| result += " #{k.to_s}='#{v.to_s}'"}
result += ">\n"
result += text
result += menu_tag_builder(node["children"], &block)
result += "</li>\n"
end
result += "</ul>"
result
end
def menu_tag(array, &block)
haml_concat(menu_tag_builder(array, &block))
end
查看
# index.haml, where config(:menu) converts the yaml below
# to an array of objects, where object[:children] is a nested array
- menu_tag(config(:menu)) do |attributes, node|
- attributes[:class] = "one two"
- node["title"]
示例 YAML 定义菜单
menu:
-
title: "Home"
path: "/home"
-
title: "About Us"
path: "/about"
children:
-
title: "Our Story"
path: "/about/our-story"
任何想法如何做到这一点,所以输出是这样的:
<ul>
<li class='one two'>
Home
</li>
<li class='one two'>
About Us
</li>
</ul>
...不是这样的:
<ul>
<li class='one two'>
Home</li>
<li class='one two'>
About Us</li>
</ul>
...因此它在全局范围内正确缩进。
感谢您的帮助, 兰斯
最佳答案
缩进良好的 Ruby 生成的 Haml 代码的诀窍是 haml_tag
helper .以下是我如何将您的 menu_tag
方法转换为使用 haml_tag
:
def menu_tag(array, &block)
return unless array
haml_tag :ul do
array.each do |node|
attributes = {}
if block_given?
text = yield(attributes, node)
else
text = node["title"]
end
haml_tag :li, text, attributes
menu_tag_builder(node["children"], &block)
end
end
end
关于ruby - 如何在 HAML 中构建嵌套菜单 "trees",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2423148/