Rails 这个 "yield" 有什么作用?

Rails what does this "yield" do?

yield 在此代码段中的作用是什么?

<body data-spy="scroll" data-target=".sidebar">
  <!-- Your timezone is <%= Time.zone %> -->
  <!-- <%= "Ruby Version is #{RUBY_VERSION}" if Rails.env =~ /test|development/ %> -->
  <%= render partial:'shared/account_status' %>
  <%= render partial:"shared/session_timeout" %>
  <div class="container">
    <%= render partial:"shared/branding" %>
    <%= render partial:"shared/nav", locals:{icons:icons, actionable_urls:actionable_urls, top_level_items:MenuItem.top_level_items_with_access_rights_for_user(current_user).sort{|a, b| a.sequence <=> b.sequence}, current_item:current_navigation_item} %>
    <div style="clear:both"></div>
    <div id="content">
      <%= render partial:"shared/flash", object:flash %>
      <%= yield %>
    </div>

  </div>
  <%= render partial:"shared/ldap_user_menu" if signed_in_as_ldap_user?  %>
</body>

解决方案

请参阅下面@Christian_Rolle 的回答

保留的 Ruby 关键字 yield 用于处理闭包(如 Proc 或 lamda)。也就是说,它是某种用于处理某些逻辑的占位符。 在 Ruby 的 Rails 视图模板中,它用于合并部分。对于像 application.html.erb 这样的布局文件,它会合并到像 index.html.erb 或 show.html.erb 这样的控制器响应模板中。 将其视为全局布局环境中控制器响应 HTML 的占位符。


阅读更多信息:Understanding yield 或大约 Ruby 个闭包: Do the Proc! ... a Ruby closureHave a lambda! ... a Ruby closure

好吧...让我们简单地谈谈它,yield 就像一个占位符或像一个容器。当您创建视图的不同部分并希望在任何特定的布局文件中显示它时,您只需在 yield 部分调用该部分即可。这就是它所做的一切。