我有多个部分可能会或可能不会包含在给定的布局中......并且它们通常只需要部分内容的javascript ...但我希望javascript加载到头部。
所以我通常会有类似的东西:
<html>
<head>
<title><%= @page_title %></title>
<%= yield :head %>
</head>
...etc
和部分1:
<% content_for :head do %>
<%= javascript_tag 'partial_one_js' %>
<% end %>
和部分2:
<% content_for :head do %>
<%= javascript_tag 'partial_two_js' %>
<% end %>
但是,无论哪个被定义为第二个都会消除第一个内容。
无法合并部分内容。
我希望能够在不做任何完全hacky的情况下连接它们。如果只有一个或两个都不存在,它也必须工作。
......我特别宁愿避免:
<html>
<head>
<title><%= @page_title %></title>
<%= yield :head_one %>
<%= yield :head_two %>
</head>
...... ick
所以...有人有解决方案吗?
答案 0 :(得分:19)
使用content_for
检索存储的内容而不是yield
。
<html>
<head>
<title><%= @page_title %></title>
<%= content_for :head %>
</head>
...etc
来自source docs:
# Note that content_for concatenates the blocks it is given for a particular
# identifier in order. For example:
#
# <% content_for :navigation do %>
# <li><%= link_to 'Home', :action => 'index' %></li>
# <% end %>
#
# <%# Add some other content, or use a different template: %>
#
# <% content_for :navigation do %>
# <li><%= link_to 'Login', :action => 'login' %></li>
# <% end %>
#
# Then, in another template or layout, this code would render both links in order:
#
# <ul><%= content_for :navigation %></ul>