加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何在HAML中构建嵌套菜单“树”

发布时间:2020-12-17 02:58:25 所属栏目:百科 来源:网络整理
导读:我正在尝试使用HAML构建一个简单的嵌套html菜单,并且我不确定如何使用 correct indentation插入元素,或者是构建嵌套树的一般最佳方法.我希望能够做到这样的事情,但无限深入: - categories.each_key do |category| %li.cat-item{:id = "category-#{category}
我正在尝试使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读