Como construir menu “árvores” aninhados em HAML
Pergunta
Eu estou tentando construir um menu simples html aninhada usando HAML e não estou certo como ir sobre como inserir os elementos com o correta recuo , ou a melhor maneira geral para construir árvores aninhadas. Eu gostaria de ser capaz de fazer algo assim, mas infinitamente profunda:
- categories.each_key do |category|
%li.cat-item{:id => "category-#{category}"}
%a{:href => "/category/#{category}", :title => "#{category.titleize}"}
= category.titleize
Parece que eu deveria ser capaz de fazer isso muito facilmente, sem recorrer a escrever as tags manualmente em html, mas eu não sou o melhor com recursividade. Aqui está o código que eu tenho atualmente vir para cima com:
View Helper
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
Ver
# 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"]
Amostra YAML definição de Menu
menu:
-
title: "Home"
path: "/home"
-
title: "About Us"
path: "/about"
children:
-
title: "Our Story"
path: "/about/our-story"
Todas as idéias como fazer isso de modo que a saída é assim:
<ul>
<li class='one two'>
Home
</li>
<li class='one two'>
About Us
</li>
</ul>
... não assim:
<ul>
<li class='one two'>
Home</li>
<li class='one two'>
About Us</li>
</ul>
... e assim é adequadamente recuado globalmente.
Obrigado pela ajuda, Lance
Solução
O truque para bem-recuado, código Haml Rubi-gerado é o haml_tag
ajudante . Aqui está como eu iria converter o seu método menu_tag
a usar 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
Outras dicas
Como sobre algo ao longo das linhas de:
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
dica impressionante, de @ Shingara me colocar na direção certa :). Isso funciona perfeitamente:
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
Se alguém pode fazer isso ainda mais curto, ou torná-lo mais fácil de personalizar os atributos nos nós aninhados, eu vou marcar esse como correta, em vez disso.
Felicidades.
É porque você enviar um HTML pur por seu ajudante. O recuo se tornar com HAML. Você pode pode gerar algum HAML no seu ajudante.