我正在用 ruby on rails 创建一个应用程序,其中有一个 items/_item.html.erb。部分内部是一个 yield 语句,因此我可以根据需要添加额外的内容。在这种情况下,我想根据调用部分的 View 向项目添加特定按钮。
这是我尝试过的,它呈现了部分,但它不呈现块:
_item.html.erb
<%= yield if block_given? %>
<div>
<%= item.name %>
</div>
someview.html.erb
...
<% render(:partial => 'items/item', :collection => current_user.items do %>
<%= "HELLO" %>
<% end %>
...
我也尝试过使用 content_for 和其他一些没有成功的东西。有没有办法能够通过 yield 在部分中呈现特定内容?我目前正在使用 Rails3
编辑:
我发现是 :collection 哈希使得无法插入块。
这两段代码都有效:
<%= render :layout => 'items/item' do %>
Hello world
<% end %>
<%= render :layout => 'items/item', :locals => {:item => current_user.items.first} do %>
Hello world
<% end %>
这意味着如果我做一个 .each 我可以完成我想要的但它会是丑陋的代码。任何人都知道解决这个问题的方法吗?
最佳答案
content_for
在这种情况下应该可以正常工作。这是我刚刚在本地仔细检查的代码。
某处.html.erb
<% content_for :foobar do %>
fubar
<% end %>
_item.html.erb
<% if content_for? :foobar %>
<%= yield :foobar %>
<% end %>
关于ruby-on-rails - 通过 =yield 在部分内呈现内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7183619/