2011-11-24 108 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 %> 

你需要什麼。