本文介绍了Rails 辅助方法:嵌套哈希到嵌套 HTML 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Rails 辅助方法来将嵌套的哈希转换为嵌套的 HTML 列表.

I am trying to write a Rails helper method to convert a nested hash into a nested HTML list.

例如:

{
  :parent => "foo",
  :children => [
    {
      :parent => "bar",
      :children => [
        {
          :parent => "baz",
          :children => []
        }
      ]
    }
  ]
}

应该变成:

<ul>
  <li>foo</li>
  <ul>
    <li>bar</li>
    <ul>
      <li>baz</li>
    </ul>
  </ul>
</ul>

散列可以有任意数量的级别,每个级别可以有任意数量的父级.

The hash may have any number of levels, and any number of parents per level.

请问实现此目标的最佳方法是什么?

What is the best way to achieve this please?

推荐答案

您可以使用递归方法将哈希渲染为嵌套列表集.将此放在您的相关帮助程序中:

You can make a recursive method to render to hash to a nested set of lists. Place this in your relevant helper:

def hash_list_tag(hash)
  html = content_tag(:ul) {
    ul_contents = ""
    ul_contents << content_tag(:li, hash[:parent])
    hash[:children].each do |child|
      ul_contents << hash_list_tag(child)
    end

    ul_contents.html_safe
  }.html_safe
end

这篇关于Rails 辅助方法:嵌套哈希到嵌套 HTML 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:24
查看更多