Difference between Yield and Content-for methods in Layouts

Mehr un NisaMehr un Nisa
2 min read

Concept of Yield in Layouts:

Yield identifies a section where content from the view should be inserted. It provides a block of area into which the entire contents of the view currently being rendered are inserted.

Use of Yield in Layouts:

For example, you created a controller-specific layout in the rails application and want to access the layout with the content of the controller.

You have the controller file name as articles_controller in your rails application as

class ArticlesController < ApplicationController
 layout "article", only: [:index]
 def index
    @articles = Article.all
  end
  def new
    @article = Article.new
  end
end

And you have created the article layout in the layout folder article.html.erb as:

<p>hello Rails</p>
<%= yield %>

There is Yield there, it represented the content of the controller after the layout content is executed.

Concept of Content-for in Layouts:

'Content-for' is used to insert dynamic content into the yield blocks within a layout from an individual view. It allows you to inject specific content into different sections of the layouts based on the needs of each view.

This is especially useful when you have common elements in your layouts for example, header, footer and sidebars etc to provide distinct content in it specific to that particular area or region. It is used for individual view files to provide content for named blocks in the layout.

Use of Content-for in Layouts:

For example, you have the layout file as application.html.erb in the layouts folder:

<!DOCTYPE html>
<html>
<head>
  <title>Your App</title>
</head>
<body>
<%= yield :header %>
<div class="main-content">
  <%= yield %>
</div>
<%= yield :footer %>
</body>
</html>

In your view file, for specific content for the header and footer, you can use this content-for as:

<% content_for :header do %>
  <header>
    <!-- Your header content here -->
  </header>
<% end %>
<h1>Welcome to My App</h1>
<p>This is the main content of the page.</p>
<% content_for :footer do %>
  <footer>
    <!-- Your footer content here -->
  </footer>
<% end %>

Conclusion:

This is the details about Yield and Content-for in the Rails Applications. I hope you found the article informative and helpful.

Before We End...

Let's connect,

Connect with me through my LinkedIn

Give A Follow on Twitter

Subscribe To my YouTube Channel

Side Projects on GitHub

0
Subscribe to my newsletter

Read articles from Mehr un Nisa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mehr un Nisa
Mehr un Nisa

I m a Software Engineer and also a YouTuber.