LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】レイアウトの作成とパーシャル【Rails Tutorial 5章まとめ】

Last updated at Posted at 2019-11-26

アプリケーションのレイアウトを作成する。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all',
                               'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application',
                               'data-turbolinks-track': 'reload' %>
    <!--[if lt IE 9]>
      <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js">
      </script>
    <![endif]-->
  </head>
  <body>
    <header class="navbar navbar-fixed-top navbar-inverse">
      <div class="container">
        <%= link_to "sample app", '#', id: "logo" %>
        <nav>
          <ul class="nav navbar-nav navbar-right">
            <li><%= link_to "Home",   '#' %></li>
            <li><%= link_to "Help",   '#' %></li>
            <li><%= link_to "Log in", '#' %></li>
          </ul>
        </nav>
      </div>
    </header>
    <div class="container">
      <%= yield %>
    </div>
  </body>
</html>

<!--[if lt IE 9]>はIE9未満のブラウザ用(いまだにIEを使う人間がいるのかどうかは定かではない)。
navタグはリンクの一覧などの「主要なナビゲーション」に使うらしい。

link_toはRailsヘルパーであり、aタグを生成する。
第一引数にリンクテキスト、第二引数にURLを指定する。
URLには名前付きルートが使える。
classを指定する場合は、第三引数にclass:をキーにしたハッシュの形で指定する(idも同じ)。

link_toのリンクテキストには、image_tagを使用することで画像を指定できる。

app/views/static_pages/home.html.erb
<%= link_to image_tag("rails.png", alt: "Rails logo"), 'http://rubyonrails.org/' %>

画像(rails.png)はapp/assets/images/に置く。
altは画像が表示されない場合に代わりに表示される文字列である。

パーシャル

パーシャルによって、レイアウトのコードをそのまとまり毎に別のファイルに分割する。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <%= render 'layouts/head' %>
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <%= yield %>
      <%= render 'layouts/footer' %>
    </div>
  </body>
</html>

<header>...</header>の部分を<%= render 'layouts/header' %>に置換している。
<header>とその中身は、パーシャル(app/views/layouts/_header.html.erb)を作成してそこに移す。
パーシャルのファイル名にはアンダーバーをつける。
renderで呼び出す場合は、アンダーバーはつけない。

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