我正在尝试使用 HAML 构建一个简单的嵌套 html 菜单,但不知道如何使用 正确的缩进, ,或者构建嵌套树的一般最佳方法。我希望能够做这样的事情,但无限深:

- 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 帮手. 。这是我如何转换你的 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

其他提示

如何沿的线的东西:

def nested_list(list)
  return unless list
  haml_tag :ul do
    list.each do |item|
      haml_tag :li do
        haml_concat link_to item["title"], item["path"]
        if item["children"]
          nested_list item["children"]
        end
      end
    end
  end
end

真棒,@ shingara的暗示把我在正确的方向:)。这工作完全:

def menu_tag(array, &block)
  return "" if array.nil?
  haml_tag :ui do
    array.each do |node|
      attributes = {}
      if block_given?
        text = yield(attributes, node)
      else
        text = node[:title]
      end
      haml_tag :li, attributes do
        haml_concat text
        menu_tag_builder(node[:children], &block)
      end
    end
  end
end

如果有人能做出更短,或使其更容易定制的嵌套节点的属性,我将标志着作为正确的,而不是这个。

干杯。

这是因为你通过你的助手发送PUR HTML。压痕成为HAML。你可以在你的助手产生一些HAML。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top