Rails使用块渲染部分 [英] Rails render partial with block
问题描述
我正在尝试重新使用我编写的提供面板样式的html组件.像这样:
I'm trying to re-use an html component that i've written that provides panel styling. Something like:
<div class="v-panel">
<div class="v-panel-tr"></div>
<h3>Some Title</h3>
<div class="v-panel-c">
.. content goes here
</div>
<div class="v-panel-b"><div class="v-panel-br"></div><div class="v-panel-bl"></div></div>
</div>
所以我看到渲染占用了一个块.我想然后我可以做这样的事情:
So I see that render takes a block. I figured then I could do something like this:
# /shared/_panel.html.erb
<div class="v-panel">
<div class="v-panel-tr"></div>
<h3><%= title %></h3>
<div class="v-panel-c">
<%= yield %>
</div>
<div class="v-panel-b"><div class="v-panel-br"></div><div class="v-panel-bl"></div></div>
</div>
我想做类似的事情:
#some html view
<%= render :partial => '/shared/panel', :locals =>{:title => "Some Title"} do %>
<p>Here is some content to be rendered inside the panel</p>
<% end %>
不幸的是,这不适用于此错误:
Unfortunately this doesn't work with this error:
ActionView::TemplateError (/Users/bradrobertson/Repos/VeloUltralite/source/trunk/app/views/sessions/new.html.erb:1: , unexpected tRPAREN
old_output_buffer = output_buffer;;@output_buffer = ''; __in_erb_template=true ; @output_buffer.concat(( render :partial => '/shared/panel', :locals => {:title => "Welcome"} do ).to_s)
on line #1 of app/views/sessions/new.html.erb:
1: <%= render :partial => '/shared/panel', :locals => {:title => "Welcome"} do -%>
...
所以它显然不喜欢=
带有块,但是如果我将其删除,则它什么也不会输出.
So it doesn't like the =
obviously with a block, but if I remove it, then it just doesn't output anything.
有人知道我该怎么做吗?我想在我网站的许多地方重复使用此面板html.
Does anyone know how to do what I'm trying to achieve here? I'd like to re-use this panel html in many places on my site.
推荐答案
虽然上述两个答案都有效(以及tony始终与之链接的示例),但我最终在上面的帖子中找到了最简洁的答案(Kornelis的评论)希茨玛(Sietsma)
While both of those answers above work (well the example that tony links to anyway) I ended up finding the most succinct answer in that above post (comment by Kornelis Sietsma)
我想render :layout
确实 我在寻找什么:
I guess render :layout
does exactly what I was looking for:
# Some View
<%= render :layout => '/shared/panel', :locals => {:title => 'some title'} do %>
<p>Here is some content</p>
<% end %>
结合:
# /shared/_panel.html.erb
<div class="v-panel">
<div class="v-panel-tr"></div>
<h3><%= title -%></h3>
<div class="v-panel-c">
<%= yield %>
</div>
</div>
这篇关于Rails使用块渲染部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!