Lan*_*ard 4 ruby tree recursion haml
我正在尝试使用HAML构建一个简单的嵌套html菜单,并且不确定如何使用正确的缩进插入元素,或者是构建嵌套树的一般最佳方法.我希望能够做到这样的事情,但无限深入:
- categories.each_key do |category|
%li.cat-item{:id => "category-#{category}"}
%a{:href => "/category/#{category}", :title => "#{category.titleize}"}
= category.titleize
Run Code Online (Sandbox Code Playgroud)
感觉我应该能够很容易地完成这个,而不需要在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
Run Code Online (Sandbox Code Playgroud)
视图
# 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"]
Run Code Online (Sandbox Code Playgroud)
示例YAML定义菜单
menu:
-
title: "Home"
path: "/home"
-
title: "About Us"
path: "/about"
children:
-
title: "Our Story"
path: "/about/our-story"
Run Code Online (Sandbox Code Playgroud)
任何想法如何做到这样输出是这样的:
<ul>
<li class='one two'>
Home
</li>
<li class='one two'>
About Us
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
......不是这样的:
<ul>
<li class='one two'>
Home</li>
<li class='one two'>
About Us</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
......所以它在全球范围内正确缩进.
谢谢你的帮助,兰斯
很好地缩进,Ruby生成的Haml代码的技巧就是haml_tag帮手.以下是我将您的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3356 次 |
| 最近记录: |