Search code examples
ruby-on-railspartials

How can I supply data to yield in my rails partial?


I'm trying to render a partial with a certain layout file. But be able to specify unique values for that specific partial. Below are the current files I have, but all that happens is the yield keywords both show the collection value. I'd like to pass a custom "title" and show the collection in the "body".

application/_news_article.html.erb

<!-- application/_news_article.html.erb  --> 
<% if news_article.report_text.present? %>
  <div class="news_article_entry">
    <div class="text-box">
      <span><%= "#{news_article.published_date.strftime("%D")}" %></span> -
      <%= "#{news_article.report_text}" %>
    </div>
    <% if news_article.impact_text.present? %>
      <div class="impact-text" data-toggle="tooltip" data-placement="bottom"
        title="<%= news_article.impact_text %>">Analysis</div>
    <% end %>
  </div>
  <hr />
<% end %>

application/_news_articles.html.erb

<!-- application/_news_articles.html.erb  --> 
<%= render partial: "news_article", collection: articles %>

layouts/_panel_box_scrollable.html.erb

<!-- layouts/_panel_box_scrollable.html.erb  --> 
<div class="panel panel-default skill-evaluation-box">
  <div class="skill-heading">
    <div class="row">
      <div class="col-xs-12">
        <%= "#{yield :title}".upcase %>
      </div>
    </div>
  </div>
  <div class="skill-body scrollable">
    <%= yield :body %>
  </div>
</div>

schools/show.html.erb

 <!-- schools/show.html.erb  --> 
 <%= render partial: 'news_articles', layout: "layouts/panel_box_scrollable", locals: { articles: @articles } %>

Solution

  • Yield is where the partial will be rendered. If you want to render a title you need to pass in a title through locals or use a variable potentially on one of your models or set in the controller. In this case if you want to render a title do something like:

    <%= render partial: 'news_articles', layout: "layouts/panel_box_scrollable", locals: { articles: @articles, title: 'My Title' } %>
    

    Then in your layout do:

    <div class="panel panel-default skill-evaluation-box">
      <div class="skill-heading">
        <div class="row">
          <div class="col-xs-12">
            <%= title.upcase %>
          </div>
        </div>
      </div>
      <div class="skill-body scrollable">
        <%= yield %>
      </div>
    </div>