LoginSignup
0
0

More than 1 year has passed since last update.

パーシャルについての備忘録[Rails]

Posted at

Railsにはパーシャル(partial)という機能があります。

これによって、htmlファイルをより簡潔に書くことができ、また管理も楽になります。

実用例

パーシャルファイルを作成する。

touch app/views/layouts/_header.html.erb

パーシャルを定義する。

app/views/layouts/_header.html.erb
<header">
  <div class="container">
    <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>

application.html.erbでパーシャルを参照できるようにする。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <%= render 'layouts/shim' %> #パーシャルを参照する。
  </head>
  <body>
    <%= render 'layouts/header' %> #パーシャルを参照する。

    <div class="container">
      <%= yield %>
      <%= render 'layouts/footer' %> #パーシャルを参照する。
    </div>
  </body>
</html>

上記の<%= render ~ %>の部分でlayoutsディレクトリ下にあるパーシャルを参照することができるようになります。

パーシャルの効果

  1. コードの管理がしやすくなる。
  2. コードが簡潔になる。
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