SB
2007-Apr-01 23:48 UTC
[Betternestedset-talk] Turning an Array of Array into Nested Lists
By way of introduction, I want to use betternestedset to generate nested comments. I figured out the generation of html tags and simply needed a way to produce an array of arrays to turn into links. Thought I''d share some useful code snippets that can maybe be improved or used by people here. Here''s a code snippet I use to generate a nested <ol> or <ul> from an array of arrays. The main difficulty I have is not being able to pass it a cycle method to create alternating styles without hard-coding it into the method (I''d love to know if someone can show me a clean way to do it). In application helper: def html_list(type, elements, options = {}, &block) items = elements.map do |element| if element.is_a?(Array) element = html_list(type, element, options, &block) else element = block.call(element) if block content_tag("li", element) end end content_tag(type, items, options) end def ul(*args, &block) html_list("ul", *args, &block) end def ol(*args, &block) html_list("ol", *args, &block) end In your views (this will be a proper nested list): <%= ul(["first", "first", ["second", ["third", "third", "third"], "second", "second", ["third", "third", "third", ["fourth", "fourth", "fourth"]]]]) {|x| link_to x, :controller => "account", :action => "signup" }%> As you can see, passing a block will help you format the objects. I haven''t yet tested this with objects but it should work in one form or another. Any other examples used by members of this list would be appreciated. Sam