ruby-on-rails-3templatesviewpartialcontent-for

Is it possible to pass html elements into a partial?


I have a partial that contains a header, a subheader and potentially one or more buttons. It is used on many different pages. Often the pages don't need buttons, so I just pass in the header and an optional subheader to the partial. However sometimes the pages need one or more buttons and the only way I've managed to allow for an arbitrary number of buttons to be passed in is using content_for. My partial looks like this:

<% if defined? page_title %>
    <header class="pageHeader">
        <div class="page-details">
            <h3><%= page_title %></h3>
            <% if defined? page_subtitle %>
                <p><%= page_subtitle %></p>
            <% end %>
        </div>
        <ul class="crud-menu nav-pills">
            <%= content_for :page_header_buttons %>
        </ul>
    </header>
<% end %>

This use of content_for nasty. Is there any way I can pass the list items / buttons into this partial? How else could I deal with this situation?


Solution

  • You could transform this partial into a layout:

    <% if defined? page_title %>
        <header class="pageHeader">
            <div class="page-details">
                 <h3><%= page_title %></h3>
                <% if defined? page_subtitle %>
                     <p><%= page_subtitle %></p>
                <% end %>
            </div>
            <ul class="crud-menu nav-pills">
                <%= yield %>
            </ul>
        </header>
    <% end %>
    

    And you would render it like that:

    <%= render layout: "your_partial_above", locals: { page_title: "page title } do %>
        <%= render "partial_with_your_buttons" %>
    <% end %>