LoginSignup
10
10

More than 5 years have passed since last update.

Middleman でも部分テンプレート活用したい!

Last updated at Posted at 2014-01-19

部分テンプレート (partial) を使いたい。

Rails では render :partial => "template_name" で部分テンプレートを利用できますが、
Middleman でも同様に部分テンプレート機能が使えます。
ただし、Middleman の場合は以下の方法で部分テンプレートを呼び出します。
(以下、ビューのファイル形式は HAML で説明します。)

呼び出し元

partial メソッドでテンプレートを描画する。
(Rials の場合と同様に) 引数にテンプレートのファイル名を指定する。

source/index.html.haml
.mami-tomoe
  = partial :tiro

呼び出し先 (部分テンプレート)

(Rials の場合と同様に) ファイル名の先頭にアンダースコアを付与する。

source/_tiro.html.haml
- 5.times do
  .special= "ティロ・フィナーレ!"

部分テンプレートに引数を渡したい。

これまた Rails の部分テンプレートと同様に、部分テンプレートに引数を渡せます。
:locals というオプションに任意の key, value を渡します。

source/index.html.haml
.mami-tomoe
  = partial :tiro, locals: { type: "デュエット" }
source/_tiro.html.haml
- 5.times do
  .special= "ティロ・#{type}!"

上記の例の場合、type を必ず指定しなければいけません。
指定しなかった場合は、変数 type を呼び出す際に NameError となります。

引数を省略した場合はデフォルト値を入れたい。

前述の例に locals で渡す値を増やしました。

source/index.html.haml
.mami-tomoe
  = partial :tiro, locals: { type: "デュエット", length: 3 }
source/_tiro.html.haml
- length.times do
  .special= "ティロ・#{type}!"

ただし、上記の例で毎回 length を指定するのは面倒だなぁ…。
指定しない場合はデフォルト値を入れたい。でも渡さないと NameError が…。
そのような時に役立つのが、部分テンプレート内での locals です。

source/index.html.haml
.mami-tomoe
  = partial :tiro, locals: { type: "デュエット" }
source/_tiro.html.haml
- legnth = locals[:length] || 5
- length.times do
  .special= "ティロ・#{type}!"

動いた! ✌('ω'✌ )三✌( 'ω' )✌三( ✌'ω')✌

10
10
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
10
10