问题描述
我已经用JBuilder创建了一个json视图.但是我想将其预加载到数据对象中,因此Backbone可以在不获取数据的情况下尽早访问数据.
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.
如何将list.json.jbuilder视图渲染到list.html.erb视图中?
How can I render the list.json.jbuilder view into my list.html.erb view?
通常没有jbuilder,我会做这样的事情:
Normally without jbuilder, I'd do something like this:
<div data-list="<%= @contents.to_json %>"></div>
在视图中调用
推荐答案
render
时,返回传递的模板或部分模板的字符串渲染;您可以根据需要将该字符串嵌入视图中.不过请注意:
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:
- 您必须在模板名称后附加后缀/扩展名.如果您不这样做,Rails可能会对您正在调用哪个模板文件感到困惑.即:它可能选择
list.html.erb
而不是list.json.jbuilder
.如果要从list.html.erb
进行此调用,则尝试呈现list.html.erb
会导致无限递归和SystemStackError.对于render
使用:format
选项似乎无效. - 您必须指定模板的合格路径;仅仅因为
list.json.jbuilder
与list.html.erb
驻留在同一目录中,它不会为"list.json"找到正确的模板. - 您需要通过
raw
传递render
调用的输出;否则,当将其嵌入到视图中时,它将被转义.
- 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.
因此,对于您的示例,假设模板位于/app/views/foo
中,则可以编写此代码:
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>
这篇关于在html视图中呈现JBuilder视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!