2011-11-24 54 views
1

我正在寻找的效果是为html框实现可重用组件。我发现人们似乎使用类似下面的例子,但它不适合我。 我:渲染局部布局不显示任何内容

# app/views/home/index.html.erb 
top 
<% render :layout => 'layouts/box' do %> 
    <p>Here is some content</p> 
<% end %> 
bottom 

# app/views/layouts/_box.html.erb 
inside box 
<%= yield %> 

最终的结果我得到呈现在浏览器上是:

top bottom 

,我仍然可以在日志中看到:

Processing by HomeController#index as HTML 
Rendered layouts/_box.html.erb (0.1ms) 
Rendered home/index.html.erb within layouts/application (1.2ms) 

所以箱子布局正在处理中。它只是没有显示任何东西。 任何想法?

我使用的是Rails 3.1.3和Ruby 1.9.2-p290。

+2

你忘了打印渲染。使用<%= render代替<%render – yoavmatchulsky

回答

2

你忘了你的输出 '渲染' 呼叫:中

<%= render ... %> 

代替

<% render ... %> 
0

也许你混了渲染部分,并通过content_for产生内容:

渲染部分:通过content_for

# app/views/home/index.html.erb 
top 
<%= render 'layouts/box' %> 
bottom 

# app/views/layouts/_box.html.erb 
Here is some content inside the box 

# result: 
top 
Here is some content inside the box 
bottom 

屈服内容:

# app/views/home/index.html.erb 
top 
<% content_for :box do %> 
Some content 
<% end %> 
bottom 

# app/views/layouts/application.html.erb 
<%= yield :box %> 
<%= yield %> 

# result 
Some content 
top 
bottom 

你可以这样做:

# app/views/home/index.html.erb 
top 
<p>Here is some content</p> 
<%= render 'layouts/box' %> 
bottom 

# app/layouts/_box.html.erb 
inside box 

通常,布局文件夹用于布局(容器)。如果您需要跨不同控制器使用部分内容,请将它放在app/views/shared/_your_partial.html.erb中。

更多的信息在这里: 的产量和content_for:http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield

对于谐音: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

+0

这并不能真正解决我的问题。或者,也许我没有得到它。我仍然没有看到我可以如何实现我的盒子组件。 –

2
<% @Var %> 

隐藏的内容

<%= @var %> 

显示内容

所以它可能是:

<%= render :layout => 'layouts/box' do %> 
    <p>Here is some content</p> 
<% end %> 

你需要什么。