简体   繁体   中英

Render html partial in JSON JBuilder

I am rendering JSON of some students using JBuilder in Rails 4. I want each student to have a "html" attribute that contains the HTML partial for a given student:

[
  { html: "<b>I was rendered from a partial</b>" }
]

I have tried the following:

json.array! @students do |student|
  json.html render partial: 'students/_student', locals: { student: student }
end

But this gives me:

Missing partial students/_student with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :haml]}.

You have to specify the partial format as Rails will look for partial with current format (json) by default. For example:

render partial: 'students/student.html.erb'

您需要指定部分格式。

json.array! @students do |student| json.html render(student, formats: [:html]) end

Here's what worked for me:

# students/index.json.jbuilder
json.array! @students do |student|
  json.html render partial: 'student.html.erb', locals: { student: student }
end

# students/_student.html.erb
<h4><%= student.name %></h4>

Rails partials use an underscore in the filename but not in the code when referenced as a string (depending on how you are loading them of course). Usually a partial called posts/_post.html.haml will be referenced in code as render :partial => 'posts/post'

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