As an example, say I have an Article
in my models
file :
Article
artname Text
title Text
keywords Text Maybe
description Text Maybe
body Markdown
parent ArticleId Maybe
user UserId
lastUpdate UTCTime
weight Int
public Bool
UniqueArt artname
deriving Typeable
I do not need to create a primary key articleId
as it is handled by Persistent.
In my routes
file:
/new/page ArticleNewR GET POST
/page/#ArticleId/edit ArticleEditR GET POST
/page/#ArticleId/delete ArticleDeleteR GET POST
/page/#ArticleId ArticleViewR GET
The #ArticleId
tells Yesod to only accept an ArticleId
as second argument in my URLs. The Article*R
are just handlers for each URL.
In Handler/Article.hs
, I need to have the corresponding function handlers. For example, if I told Yesod of the ArticleViewR
GET handler, I need to define the following function:
getArticleViewR :: ArticleId -> Handler Html
getArticleViewR articleId = do
-- The article
article <- runDB $ get404 articleId
-- The parent article (if any)
let parentIdM = articleParent article
parentM <- case parentIdM of
Just parentId -> runDB $ get parentId
Nothing -> return Nothing
-- The child articles
children <- runDB $ selectList [ArticleParent ==. Just articleId]
[Asc ArticleWeight, Asc ArticleTitle]
-- Author
author <- runDB $ get (articleUser article)
defaultLayout $ do
setTitle $ toHtml (articleTitle article)
setDescription $ articleDescription article
setKeywords $ articleKeywords article
setAuthor $ userUsername <$> author
$(widgetFile "article/view")
That’s basically how you link each piece.