我想做"content_for"*两次*到相同的yield-block - >怎么样?

Tar*_*ast 10 layout ruby-on-rails

我有多个部分可能会或可能不会包含在给定的布局中......并且它们通常只需要部分内容的javascript ...但我希望javascript加载到头部.

所以我通常会有类似的东西:

<html>
  <head>
    <title><%= @page_title %></title>
    <%= yield :head %>
  </head>
...etc
Run Code Online (Sandbox Code Playgroud)

在部分1中:

<% content_for :head do %>
      <%= javascript_tag 'partial_one_js' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

在第2部分:

<% content_for :head do %>
      <%= javascript_tag 'partial_two_js' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

但是,无论哪个定义为第二个都会消除第一个内容.

没有办法合并部分.

我希望能够连接它们而不做任何完全hacky的事情.如果只有一个或两个都不存在,它也必须工作.

......我特别宁愿避免:

<html>
  <head>
    <title><%= @page_title %></title>
    <%= yield :head_one %>
    <%= yield :head_two %>
  </head>
Run Code Online (Sandbox Code Playgroud)

...... ick

那么......有人有解决方案吗?

Dou*_*rer 20

使用content_for检索存储的内容,而不是yield.

<html>
  <head>
    <title><%= @page_title %></title>
    <%= content_for :head %>
  </head>
...etc
Run Code Online (Sandbox Code Playgroud)

来自源文档:

# 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>
Run Code Online (Sandbox Code Playgroud)