[Ruby] [Rails] Learn yield to understand content_for

1 minute read

Split common layout and individual layout with yield

In Rails, the common layout is basically applied to the application.html.erb, and the variable part is managed in the body tag in the action.html.erb.

Here, yield is used to manage by dividing. Let’s look at an example! !!

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Sample</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag'application', media:'all','data-turbolinks-track':'reload' %>
    <%= javascript_include_tag'application','data-turbolinks-track':'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

What should be noted is yield. The split file is entered here. This is how to use yield. Now, let’s put in the content_for from here and think about it! This time, let’s consider a program that changes the title.

How to use #content_for and yield

content_for is used when displaying from the individual layout to the common layout. ** So let’s look at an example.

application.html.erb

<title><%= yield :title %></title>

By doing this, you can change the title part variably. It is often used when the layout changes many times in one application.

app/views/hello/index.html.erb
<% content_for :title do %>
    hello#index title
<% end %>

<h1>hello#index</h1>
<p>Find me in app/views/hello/index.html.erb</p>

Here, pay attention to content_for :title do to end. This part reacts with yield :title and enters. The actual image is as follows.

<title>hello#index title</title>

By the way, the default value can be added as follows.

<title><%= content_for?(:title)? yield(:title) :"Sample"%></title>

If there is content_for in content_for?, yield(:title) is read, otherwise the title is “Sample”. (It’s a ternary operator.)

How is it actually used?

<!DOCTYPE html>
<html>
  <head>
    <title>Sample</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag'application', media:'all','data-turbolinks-track':'reload' %>
    <%= javascript_include_tag'application','data-turbolinks-track':'reload' %>
  </head>

  <body>
    <header>Header design</header>
      <div class="notice">
        <%= content_for?(:notice) ?yield(:notice) %>
      </div>
      <%= yield %>
  </body>
</html>

Notice from the bottom of the header. notice (Imagine a notice here.) When there is a notice, I wrote a program to display yield(:notice).

If you want to display the “Notification” in all layouts but want to change the content, feel as follows.

<%= yield(:notice) %>

With split (mutable) files

<%= content_for :notice do%>
  <p>Attention! </p>
<% end %>
<%= content_for :notice do%>
  <p>Great deals! </p>
<% end %>

By doing so, you can change the common layout part for each page.

Tags: ,

Updated: