[Ruby] [Ruby on Rails] A memorandum of layout templates

1 minute read

This is the first draft. We would appreciate it if you could point out any deficiencies.

I’m studying Ruby on Rails. I wasn’t sure why the content coded in the view file was displayed properly in the browser even though it was not enclosed in the DOCTYPE declaration or HTML tags, but I understood the layout template and it was refreshing, so I will leave it as a memorandum.

What is a layout template?

It is a file that is automatically created in the following directory when you create an application with rails.
app/views/layouts/application.html.erb

Normally, from the action defined in the controller, if there is a view file, it seems that the file is called, but in reality, the view file created in the layout template is embedded and returned.

Example) When creating a controller called posts
app/controllers/posts_controller.rb

posts_controller.rb


class PostsController < ApplicationController
  def index
  end
end

app/views/posts/index.html.erb

erb:index.html.erb


<h1>top page</h1>

Actually, what is returned as a response is the view file ** index.html.erb ** called in ** <% = yield%> ** in the <body> tag of the template file below. It is said that it has been returned.

app/views/layouts/application.html.erb

erb:application.html.erb


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

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

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

index.html