Rails 使用块渲染部分内容
我正在尝试重新使用我编写的提供面板样式的 html 组件。像这样:
<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>
所以我看到渲染需要一个块。我想然后我可以做这样的事情:
# /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 %>
不幸的是,这不适用于此错误:
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 -%>
...
所以它不喜欢带有块的 =
,但是如果我删除它,然后它就不会输出任何内容。
有谁知道如何做我想在这里实现的目标?我想在我网站的许多地方重复使用这个面板 html。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据已接受的答案,这对我使用 Rails 4 来说效果很好。
我们可以这样渲染面板:
< img src="https://i.sstatic.net/s1uyO.png" alt="在此处输入图像描述">
这需要一个辅助方法和一个共享视图:
辅助方法 (ui_helper.rb)
View ( /ui/panel.html.haml)
Based on the accepted answer this is what worked well for me using Rails 4.
We can render a panel as such:
This requires a helper method and a shared view:
helper method (ui_helper.rb)
View (/ui/panel.html.haml)
我认为如果你先将它分配给一个变量然后输出它,它会起作用(只是做了快速脏测试)。
I think it will work (just did quick dirty test) if you assign it to a variable first and then output it.
虽然上面的两个答案都有效(好吧,托尼链接到的例子),但我最终在上面的帖子中找到了最简洁的答案(Kornelis Sietsma 的评论),
我猜
render :layout
确实正是我正在寻找的东西:结合:
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)
I guess
render :layout
does exactly what I was looking for:combined with:
这是基于之前答案的替代方案。
在
shared/_modal.html.erb
上创建您的部分:在
application_helper.rb
上定义您的方法:从任何视图调用它:
Here's an alternative based on previous answers.
Create your partial on
shared/_modal.html.erb
:Define your method on
application_helper.rb
:Call it from any view:
您可以使用捕获助手,甚至可以在渲染调用中内联:
和在共享/面板:中,
这将产生:
请参阅 http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html
You can use the capture helper, and even inline in the render call :
and in shared/panel:
which will produce:
See http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html