开发者

Recfactor html string using content_tag

I put together a nested unordered list in a helper method using a string. The code is okay, but I'd prefer to use the content tag method if possible. Here's what I have:

def show_element_content(element_types, site)
  last = get_element_type_name(element_types.first.name)
  output = "<li>#{last}<ul>"
  if last.nil?
    raise "ElementReturnedNullException - this shouldn't happen."
  else
    element_types.each do |ele|
      if last != get_element_type_name(ele.name)
        last = get_element_type_name(ele.name)
        output << "</ul></li><li>#{last}<ul>"
      end
      output << "<li>#{link_to get_element_content(ele.name), site_element_type_path(site, ele.name)}</li>"
    e开发者_如何学Cnd
    output << "</ul></li>"
  end
  output.html_safe
end

def get_element_type_name(ele)
  ele.split(" ")[0]
end

def get_element_content(ele)
  words = ele.split(" ")
  words[1..words.size].join(" ")
end

The first method is the one i output in the view. Here's what it does:

It splits each element_type by spaces, as there's a sort of category name persay in each one as the first word. Such as City, State or Franchise. Those words are in the higher up LI tags. Like so:

<ul>
  <li>City</li>
  <li>State</li>
</ul>

Then it loops through each element type, appending each one as a nested list. When the first word changes, it closes that nested list and li tag, to create a new one. The rendered html looks like this:

<ul>
  <li>City
    <ul>
      <li>CTA 1</li>
      <li>P1 S1</li>
      <li>P1 S2</li>
      <li>Sub2</li>
    </ul>
  </li>
</ul>

How can I do this using content_tag since i open and close the tags based on various conditions? I know it kind of makes sense to categorize these in another model, but to just do that for the presentation layer I think would be overkill.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜