LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby on Rails】レイアウトテンプレートの備忘録

Posted at

初稿です。不備がありましたらご指摘いただけると幸いです。

Ruby on Railsを勉強中です。ビューファイルでコーディングした内容が、なぜDOCTYPE宣言やHTMLタグで囲ってないのにブラウザできちんと表示されるか不明だったのですが、レイアウトテンプレートを理解してスッキリしたので備忘録として残しておきます。

レイアウトテンプレートとは?

railsでアプリケーションを作成した際に、以下のディレクトリに自動で作成されるファイルです。
app/views/layouts/application.html.erb

通常、コントローラーで定義したアクションから、ビューファイルがある場合はそのファイルが呼ばれているように見えますが、実際はレイアウトテンプレートの中に作成したビューファイルが埋め込まれて返しているとのこと。

例)postsというコントローラーを作成した場合
app/controllers/posts_controller.rb

posts_controller.rb
class PostsController < ApplicationController
  def index
  end
end

app/views/posts/index.html.erb

index.html.erb
<h1>トップページ</h1>

実際、レスポンスとして返しているのは、下記テンプレートファイルの

タグ内にある<%= yield %>に呼び出されたビューファイルindex.html.erbが埋め込まれて返されているとのこと。

app/views/layouts/application.html.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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0