scalaのWebフレームワーク liftで遊ぶ(3) - こんにちわ世界
目次はこちら。
scalaのWebフレームワーク liftで遊ぶ 目次 - ゆろよろ日記
まずはHello worldをやってみる。
静的なページを追加する
staticなページや画像などはsrc/main/webapp以下に配置するようだ。ふつーのwebアプリだね。
src/main/webapp以下に、以下の内容をtest.htmlというファイル名で作成する。
test.html
<html xmlns="http://www.w3.org/1999/xhtml"> <body> Hello Friends! </body> </html>
http://localhost:8080/test.htmlでアクセス。ちゃんと見える。
don't forget the attribute xmlns="http://www.w3.org/1999/xhtml". Without it, the xml content of page will be displayed.
どうやらXHTMLじゃないとダメらしい。
SiteMapへの追加
liftでのデフォルトページ(http://localhost:8080)に、独自のSiteMapを追加することができる。
個々のSiteMapにはパーミッションを設定できるらしいが詳しいことは不明。
デフォルトのSiteMapは、src/main/scala/bootstrap/liftweb/Boot.scalaで定義されているので、ここに追加すればよいようだ。
Boot.scalaのbootメソッドにすでにSiteMapを追加している箇所があるので、そこに新たに追加する。
Boot.scala
// Build SiteMap //val entries = Menu(Loc("Home", "/", "Home")) :: User.sitemap val entries = Menu(Loc("Home", "/", "Home")) :: Menu(Loc("Test", "/test", "Test Page")) :: User.sitemap LiftRules.setSiteMap(SiteMap(entries:_*)) S.addAround(User.requestLoans)
entriesというListにMenuオブジェクトを追加すればよいってことかな?
lift:surroundでテンプレートを適用する。
test.htmlのHello Friends!を
要はレイアウトを適用できるってこと。
じゃあ、適用されるレイアウトはどこにあるかっていうと、デフォルトのレイアウトはsrc/main/webapp/templates-hidden/default.htmlにある。
このテンプレートの中の
erbだとyeildしているみたいな。
src/main/webapp/templates-hidden/default.htmlの一部
<div class="column span-17 last"> <lift:bind name="content" /> </div>
test.htmlをこんな風に書き換えて実行すると、メニューとかが出るよ!
test.html
<lift:surround with="default" at="content"> Hello Friends! </lift:surround>
lift:snippetでscalaプログラムからの出力を埋め込む
今までは静的なページの出力だったが、lift:snippetを利用することで動的に出力を行うことができる。
html内に
test.htmlをこんな風に書き換える。
test.html
<lift:surround with="default" at="content"> Hello <lift:snippet type="Friends:show" />! </lift:surround>
では、この内容を出力するclassを作る必要がある。
Friends:showは、Friendsクラスでdef showとして定義された関数の戻り値を出力するという意味らしい。
で、Friendクラスを作成する。
src/main/scala/com/yuroyoro/hello/snippet/Friends.scala
package com.yuroyoro.snippet class Friends { def show = <span>Scala</span> }
コードの中にいきなりHTMLが出てるけど、これはscalaの機能であるXMLリテラルを利用している。
scalaではコードの中にいきなりXMLを書いてそれをリテラルとして扱える。
実行してみると、出力される文字が置き換わっている。
この例だとあまり動的な感じがしないので、現在時刻でも出してみる。
test.htmlに
<html xmlns="http://www.w3.org/1999/xhtml"> <body> <lift:surround with="default" at="content"> Hello <lift:snippet type="Friends:show" />! <lift:snippet type="Friends:show_date" /> </lift:surround> </body> </html>
Friends.scalaにshow_dateメソッドを追加。
Friends.scala
package com.yuroyoro.snippet import java.util.{Date, Locale} import java.text.DateFormat._ class Friends { def show = <span>Scala</span> def show_date = { val now = new Date <span>{getDateInstance(LONG, Locale.JAPANESE) format now}</span> } }
snippetとして定義するメソッドは、scala.xml.NodeSeqを返す必要があるらしい。
いきなりStringとか返しても何も表示されなかった。