Yesod でアプリを作る 3
-
付与されたタグ:
- Haskell
次にBlogのモデルを作成。config/routeに以下を追加する。
Post name Text title Text content Html createdAt UTCTime default=CURRENT_TIMESTAMP deriving
ただし、これだけではUTCTimeが定義されてないというエラーになるので次の作業が必要となる。
- blog.cabal の build-depends に time を追加する。
- Model.hsにimport Data.Timeを追加する。
サーバーの出すログを見ると自動的にPostのモデルが作成されたことが確認できる。
次にURLルーティングを定義する。config/routeを開いて以下を追加する。
/blog BlogR GET
するとyesodのサーバーが自動的にファイルをコンパイルして次のようなエラーを出す。
Rebuilding application... Forcing recompile for ./Foundation.hs because of config/routes Forcing recompile for ./Foundation.hs because of messages/en.msg Forcing recompile for ./Foundation.hs because of templates/default-layout-wrapper.hamlet Forcing recompile for ./Foundation.hs because of templates/default-layout.hamlet Building blog-0.0.0... Preprocessing library blog-0.0.0... [5 of 8] Compiling Foundation ( Foundation.hs, dist/build/Foundation.o ) [6 of 8] Compiling Import ( Import.hs, dist/build/Import.o ) [7 of 8] Compiling Handler.Home ( Handler/Home.hs, dist/build/Handler/Home.o ) [8 of 8] Compiling Application ( Application.hs, dist/build/Application.o ) Application.hs:27:1: Not in scope: `getBlogR' Build failure, pausing... Rebuilding application... Building blog-0.0.0... Preprocessing library blog-0.0.0... [8 of 8] Compiling Application ( Application.hs, dist/build/Application.o ) Application.hs:27:1: Not in scope: `getBlogR' Build failure, pausing...
getBlogRというハンドラが定義されてないことによりエラーが起きている。このようなエラーチェックが行われるため定義忘れなどのミスが発生しない。次にハンドラの定義を行う。Handler/Blog.hsを作成して次のように入力する。
module Handler.Blog where import Import import Yesod.Form.Nic (YesodNic, nicHtmlField) instance YesodNic App getBlogR :: Handler RepHtml getBlogR = do posts <- runDB $ selectList [] [Desc PostTitle] defaultLayout $ do setTitle "Blog Index" $(widgetFile "blog")
- blog.cabalのexposed-moduleにHandler.Blogを追加する
- Application.hsに import Handler.Blog を追加する
それが終わったあとの状態ではテンプレートが定義されてないということでエラーが起きている。次にテンプレートを作成する。templates/blog.hamleを次のように作成する。
<h1>Posts (/blog/)</h1> $if null posts <p> There are no articles in the blog $else <table border="1"> <tr><th>Name</th><th>Title</th><th>timestamp</th><th>Action</th> $forall Entity postId post <- posts <tr> <td> #{postName post} <td> #{postTitle post} <td> #{show $ postCreatedAt post}
これで http://localhost:3000/blog にアクセスするとblogのトップが表示される。データがないので何も表示されない。次にblogの記事を投稿する部分を作成する。