简体   繁体   中英

How do you render a partial to a hash value in JBuilder?

I have a tree-like object graph that resembles the following:

{
  :name => "Grandparent",
  :children => {
    :child_a => {
       :name => "Parent A",
       :children => {
         :grandchild_a_a => {
           :name => "Child A-A",
           :children => {}
         }
         :grandchild_a_b => {
           :name => "Child A-B"
           :children => {}
         }
       }
    }
    :child_b => {
       :name => "Parent B",
       :children => {}
    }
  }
}

I want to generate JSON that mirrors this structure. I don't know how deep the child nesting goes, and the attributes are the same for each level. The keys in the children hash are significant and must be preserved.

I want to use a JBuilder partial to represent a level, and then call it recursively. Here's my template thus far:

# _level_partial.json.jbuilder
# passing the above object graph as :level
json.name level[:name]
json.children do
  level[:children].each do |key, child|
    # How do I map the following to the given key?
    json.partial! "level_partial", :level => child
  end
end

I can generate the JSON for each child through the partial call easily enough, but that inserts it directly into the JSON output. How do I map the results of the partial to a particular hash/object key?

I've found an answer. Although it appears to be largely undocumented, JBuilder.set! can accept a block instead of an explicit value. That block can call the partial, which is then assigned to the hash.

json.name level[:name]
json.children do
  level[:children].each do |key, child|
    json.set! key do
      json.partial! "level_partial", :level => child
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM