如何在我的 rails 部分中提供数据以产生收益?

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

我正在尝试使用某个布局文件渲染部分内容。但是能够为该特定部分指定唯一值。以下是我当前拥有的文件,但所发生的只是 yield 关键字都显示 collection 值。我想传递自定义 "title" 并在 "body".

中显示 collection

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 } %>

Yield 是局部渲染的地方。如果你想渲染一个标题,你需要通过 locals 传递一个标题,或者在你的一个模型上使用一个变量,或者在控制器中设置一个变量。在这种情况下,如果您想呈现标题,请执行以下操作:

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

然后在你的布局中做:

<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>