日曜日, 5月 17, 2009

[Lift] より簡素に!

Liftの勉強をしてます。Webなフレームワークって便利ですね。
snippetで多用するbindについて、The Loopさんを参考に確認を。

まず、以下の書き方がサンプル的に分かりやすいモノ。

VIEW:
    <lift:helloDB.tstForm form="post">
    <testBox:lines>Lines</testBox:lines>
    <testBox:desc>To Do</testBox:desc>
    <testBox:submit>submit</testBox:submit>
    </lift:helloDB.tstForm>
SNIPPET:
    def tstForm(argForm: NodeSeq) = {
// とりあえずモデルオブジェクトを作成(!)
val hellom = HelloModel.create;

// 入力を受け取り保存するかを判断
def checkAndSave(): Unit = hellom.validate match {
// S.noticeでに値を出力
case Nil => hellom.save ; S.notice("Added "+hellom.desc)
case xs => S.error(xs) ; S.mapSnippet("helloDB.tstForm", doForm)
// S.redirectTo("/")は不要
// →何にせよ最後にdoFormしているから(再描画される)
}

// テンプレートへバインドする関数
def doForm(argForm: NodeSeq) = {
bind("testBox", argForm,
//"lines" -> toShow.toString,
"lines" -> toShow, // toShowでXMLを返すようにするから
"desc" -> hellom.desc.toForm,
"submit" -> submit("SAVE", checkAndSave)); // ボタンもタグ必要
}

// バインド実行(上の関数を)
doForm(argForm);
}

で、これをより簡単に書くと(HTML的な変更点はlabelで囲むこと)。

VIEW:
    <lift:helloDB.tstForm form="post">
    <testBox:lines>Lines</testBox:lines>
    <label for="desc">
        <testBox:desc>To Do</testBox:desc>
    </label>
    <testBox:submit>submit</testBox:submit>
    </lift:helloDB.tstForm>
SNIPPET:
    def tstForm(argForm: NodeSeq): NodeSeq = {
val hellom = HelloModel.create;

bind("testBox",argForm,
"lines" -> toShow, // toShowでXMLを返すようにするから
"desc" -> SHtml.text(hellom.desc, hellom.desc(_)), // descカラムへ書込み
"submit" -> SHtml.submit("SAVE", hellom.save)
)
}

なるほどー。かっこいい。