Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does “yield” do?

What does yield do in ruby on rails?

<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>
like image 421
Juan Martin Avatar asked Oct 13 '25 01:10

Juan Martin


1 Answers

It tells Rails to put your view content to this block (which is called by yield) at that place in the layout file.

Checkout the rails guide to learn more about the ActionView.
https://guides.rubyonrails.org/action_view_overview.html

As pointed out by @Aleksei Matiushkin, yield is pure ruby, so you should also learn more about that in your own time.

Here's a (my) visual presentation to explain what happened on that line:

view.html.erb:

<p>Hello there!</p>
<p>I'm a content from view</p>

layout.html.erb:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

Now the results will be like this:

<!DOCTYPE html>
<html>
  <head>
  </head>

  <body>
    <p>Hello there!</p>
    <p>I'm a content from view</p>
  </body>
</html>
like image 133
vpibano Avatar answered Oct 14 '25 15:10

vpibano