質問

私がいるという簡単な入れ子のhtmlを使ったメニュー HAML、いくかを挿入し、要素の 正しいインデント, またはベスト構築することが可能となる入れ子。すればよいのでしょうかできないようなことが無限に深い:

- 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