0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsの超短縮系partialの書き方【部分テンプレート】

Last updated at Posted at 2017-02-16
<%= render @notes %>

このようなめちゃめちゃ短い形で部分テンプレートを使用できます。

これを使うときは上記の例なら
views/notes/_note.html
というディレクトリ構造にしておく必要があります。

renderの指定 → @複数形
ディレクトリ名 → 複数形
partial名(部分テンプレート名) → _単数形

実際に書いた例はこんなところです。

views/notes/index.html.haml
!!!
%html
  %body
    .top-bar
    .wrapper
      .notes
        .notes__header
        .notes__search-bar
        .notes__body
          = render @notes # ここで部分テンプレートの読み込みをしています
      = render partial: "shared/content"
views/notes/_note.html.haml
// 部分テンプレート内での変数名は note が勝手に指定されます。
// 変数noteにそれぞれの@noteが都度入ってくる感じです。
= link_to note_path(note) do
  .notes__body__box
    .notes__body__box__title
      = note.title

    %hr.notes__body__box__line/

    .notes__body__box__body
      = note.body

スクリーンショット(それぞれの@noteのtitleとbodyを読み込んでいます)
スクリーンショット 2017-02-16 13.40.47.png

まとめ

今回の手法を使うと見やすく短く書けます!
railsはきちんと乗っかってあげると素晴らしく効率的に、いい感じにやってくれますね。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?