In Rails, ** common layout ** is basically applied to ʻapplication.html.erb, and ** variable part ** is managed in
body tag in ʻaction.html.erb
.
Here, yield
is used to split and manage. Let's see 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>
Of note is the yield
. The split file is stored here. This is how to use yield. Now, let's think about it by inserting content_for
from here! This time, let's consider a program that changes the title.
content_for
is used when displaying from ** individual layout to common layout. ** Let's take 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 several times in one app.
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>
Notice here from content_for: title do
to ʻend. This part will react with
yield: title` and enter. Actually, the image is as follows.
<title>hello#index title</title>
By the way, you can also set the default value as follows.
<title><%= content_for?(:title) ? yield(:title) : "Sample"%></title>
If content_for?
has content_for
,yield (: title)
is loaded, otherwise the title will be" Sample ". (It's a ternary operator.)
<!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>
Pay attention to the bottom of header
. notice
(Imagine a notification here.) I am writing a program that displaysyield (: notice)
when there is a notification.
If you want to display "Notice" in all layouts but want to change the content, you can do it as follows.
<%= yield(:notice) %>
With split (variable) files
<%= content_for :notice do%>
<p>Caution!</p>
<% end %>
<%= content_for :notice do%>
<p>Great news!</p>
<% end %>
You can also change the common layout part for each page.
Recommended Posts