Article title Text content Html derivingAs `Html` is not an instance of `Read`, `Show` and `Eq`, we had to add the `deriving` line. If you forget it, there will be an error. After the route and the model, we write the handler. First, declare a new Handler module. Add `import Handler.Blog` inside `Application.hs` and add it into `yosog.cabal`. Let's write the content of `Handler/Blog.hs`. We start by declaring the module and by importing some block necessary to handle Html in forms.
module Handler.Blog
( getBlogR
, postBlogR
, getArticleR
)
where
import Import
-- to use Html into forms
import Yesod.Form.Nic (YesodNic, nicHtmlField)
instance YesodNic Yosog
Remark: it is a best practice to add the YesodNic instance inside `Foundation.hs`.
I put this definition here to make things easier but you should see a warning about this orphan instance.
To put the include inside Foundation.hs is left as an exercice to the reader.
_Hint: Do not forget to put `YesodNic` and `nicHtmlField` inside the exported objects of the module._
entryForm :: Form Article
entryForm = renderDivs $ Article
<$> areq textField "Title" Nothing
<*> areq nicHtmlField "Content" Nothing
This function defines a form for adding a new article.
Don't pay attention to all the syntax.
If you are curious you can take a look at Applicative Functor.
You just have to remember `areq` is for required form input.
Its arguments being: `areq type label default_value`.
-- The view showing the list of articles
getBlogR :: Handler RepHtml
getBlogR = do
-- Get the list of articles inside the database.
articles <- runDB $ selectList [] [Desc ArticleTitle]
-- We'll need the two "objects": articleWidget and enctype
-- to construct the form (see templates/articles.hamlet).
((_,articleWidget), enctype) <- generateFormPost entryForm
defaultLayout $ do
$(widgetFile "articles")
This handler should display a list of articles.
We get the list from the DB and we construct the form.
Just take a look at the corresponding template:
Articles
$if null articles
-- Show a standard message if there is no article
_{MsgNoEntries}
$else
-- Show the list of articles
$forall article <- articles
-
#{articleTitle (snd article)}