问题
I've created a json view with JBuilder. But I want to preload this into a data object, so Backbone has access to the data early on without fetching for it.
How can I render the list.json.jbuilder view into my list.html.erb view?
Normally without jbuilder, I'd do something like this:
<div data-list="<%= @contents.to_json %>"></div>
回答1:
render
, when called from within a view, returns a string rendering of the passed template or partial; you can embed that string into your view as you like. Note though that:
- You have to append your template name with the type suffix/extension. If you don't, Rails may get confused about which template file you're calling; ie: it might choose
list.html.erb
instead oflist.json.jbuilder
. If you're making this call fromlist.html.erb
, trying to renderlist.html.erb
results in infinite recursion and a SystemStackError. Using the:format
option forrender
doesn't appear to work. - You have to specify the qualified path to the template; it won't find the right template for "list.json" just because
list.json.jbuilder
resides in the same directory aslist.html.erb
. - You need to pass the output of the
render
call throughraw
; otherwise, it will get escaped when it gets embedded into the view.
So, for your example, you might write this, assuming your templates were in /app/views/foo
:
<div data-list="<%= raw render(:template => "foo/list.json", :locals => { :contents => @contents }) %>"></div>
来源:https://stackoverflow.com/questions/14459750/render-a-jbuilder-view-in-html-view