Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
282 lines (206 sloc) 9.29 KB
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="">
<title><![CDATA[Category: Snap | Norm 2782]]></title>
<link href="" rel="self"/>
<link href=""/>
<name><![CDATA[Jurriën Stutterheim]]></name>
<generator uri="">Octopress</generator>
<title type="html"><![CDATA[Using digestive-functors with Heist]]></title>
<link href=""/>
<content type="html"><![CDATA[<p>In this post we will make <em>digestive-functors</em> and <em>Heist</em> play together
nicely. We will see how we can create and validate forms using vanilla
<em>digestive-functors</em> and render these, together with potential validation
errors, in a Heist template.</p>
<!-- more -->
<p>Currently this post is secretly just here to allow me to play with
<p>This post assumes you are familiar with the snaplet infrastructure
(if not: <a href="">tutorial</a>)
and that you are more or less comfortable with defining routes and rendering
templates with Heist (again:
<a href="">tutorial</a>). If this is not the
case, you might want to read some of the tutorials on the Snap website first.
This post also assumes that you know how to work with the <em>digestive-functors</em>
library (see
<a href="">one of</a>
<a href="">Jasper's tutorials</a>).</p>
<p>Since this post is written as a Literate Haskell file, we first define
some imports and other boilerplate:</p>
<p>``` haskell</p>
<blockquote><p>{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}</p>
<p>module Site (app) where</p>
<p>import Control.Applicative
import Control.Monad.State
import Data.Lens.Template
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Heist
import Text.Blaze
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Internal (HtmlM(..))
import Text.Blaze.Renderer.XmlHtml
import Text.Digestive
import Text.Digestive.Forms.Snap
import Text.Digestive.Blaze.Html5
import qualified Text.Email.Validate as E
import Text.Templating.Heist</p></blockquote>
<p>Since we are using Snap 0.7 at the moment of writing, we start by defining
out snaplet state type, generating some lenses using Template Haskell and
defining a handy type synonym for our handlers. We also want to use Heist,
so we need to define a <code>HasHeist</code> instance for our <code>App</code> type as well.
And, since this is a snaplet, we need to define our snaplet initialiser.</p>
<p>``` haskell</p>
<blockquote><p>data App
= App
{ _heist :: Snaplet (Heist App)
<p>makeLens ''App</p>
<p>type AppHandler = Handler App App</p>
<p>instance HasHeist App where
heistLens = subSnaplet heist</p>
<p>app :: SnapletInit App App
app = makeSnaplet "hdf"
"An example of digestive-functors and Heist playing nicely together."
Nothing $ do</p>
<pre><code>h &lt;- nestSnaplet "heist" heist $ heistInit "resources/templates"
addRoutes [ ("/", formHandler) ]
return $ App h
<p>Having written all the boilerplate, we can get started with defining our form.
In this case it's a simple login form with a plain textfield, a password field,
a remember me checkbox and a login button.</p>
<p>When the form has been validated, we want to store the form data in a custom
<p>``` haskell</p>
<blockquote><p>data LoginData
= LoginData
{ emailAddress :: Text
, password :: Text
, rememberMe :: Bool }</p></blockquote>
<p>Defining the form is straight-forward if you are used to working with
<em>digestive-functors</em>. The form is wrapped in divs for better styling options
and we attach validators to make sure that we get a valid email address and a
long enough password. The <code>isValid</code> function comes from the <em>email-validate</em>
<p>``` haskell</p>
<blockquote><p>loginForm :: Form AppHandler SnapInput Html (FormHtml Html) LoginData
loginForm = (\e p r _ -> LoginData e p r)
&lt;$> mapViewHtml H.div (</p>
<pre><code> label "Email address: "
++&gt; inputText Nothing `validate` isEmail
&lt;++ errors)
<p> &lt;*> mapViewHtml H.div(</p>
<pre><code> label "Password: "
++&gt; inputPassword False `validate` longPwd
&lt;++ errors)
<p> &lt;*> mapViewHtml H.div (</p>
<pre><code> label "Remember me?"
++&gt; inputCheckBox True)
<p> &lt;*> mapViewHtml H.div (</p>
<pre><code> submit "Login")
<p>isEmail :: Validator AppHandler Html Text
isEmail = check "Invalid email address" (E.isValid . T.unpack)</p>
<p>longPwd :: Validator AppHandler Html Text
longPwd = check "Password needs to be at least six characters long"</p>
<pre><code> $ \xs -&gt; T.length xs &gt;= 6
<p>Up to this point we have not seen anything new yet, so lets start with
something a bit more interesting. For most of my Snap apps I use the following
function to render a form:</p>
<p>``` haskell</p>
<blockquote><p>showForm :: AttributeValue -> AttributeValue -> FormHtml (HtmlM a) -> Html
showForm act mth frm =
let (formHtml', enctype) = renderFormHtml frm
in H.form ! A.enctype (H.toValue $ show enctype) ! A.method mth</p>
<pre><code> ! A.action act $ formHtml' &gt;&gt; return ()
<p>It takes an <code>AttributeValue</code> containing the target of the form, an
<code>AttributeValue</code> containing the HTTP request method and a form as produced by
the <code>eitherSnapForm</code> function we will see below, resulting in a rendered form
of type <code>Html</code>.</p>
<p>Now for the request handler, which is where most of the action will take place.
We want to make our lives easy, so we call in the help of the
<em>digestive-functors-snap</em> library, which provides the <code>eitherSnapForm</code>
function. This function can be applied to a <em>digestive-functors</em> form and a
form name, after which it will use the Snap API to parse the request. Before
continuing, lets have a look at some code:</p>
<p>``` haskell</p>
<blockquote><p>formHandler :: AppHandler ()
formHandler = do
res &lt;- eitherSnapForm loginForm "login-form"
case res of</p>
<pre><code>Left form -&gt; do
let nodes = renderHtmlNodes $ showForm "/" "post" form
heistLocal (bindSplice "formElm" (return nodes)) $ render "formTpl"
Right (LoginData e p r) -&gt; writeBS "Success!"
<p>The result of <code>eitherSnapForm</code> is an <code>Either</code> value. When the form has not been
submitted yet, or if a submitted form failed validation, the result will be a
<code>Left</code> constructor containing a form of type <code>FormHtml (HtmlM a)</code>. When a form
has been submitted and has succesfully passed validation, we will get a <code>Right</code>
value containing the constructor applied in our form (in this case the
<code>LoginData</code> constructor).</p>
<p>Rendering the form is done when we get a <code>Left</code> result. As it turns out, it is
almost trivially easy to render the form in Heist. To bind the form as a Heist
splice, we first need to render it to an <code>Html</code> value using our <code>showForm</code>
function. Since Heist cannot work with values of type <code>Html</code>, we have to
convert the <code>Html</code> to something Heist does understand. Luckily, the xmlhtml
library provides us with a function that does just that: <code>renderHtmlNodes ::
Html -&gt; [Node]</code>. Heist loves a list of <code>Node</code>s, so all we need to do is
<code>return</code> it to the <code>Splice</code> context so we can bind it as a splice to our
<p>The final piece of the puzzle is the template in which the form needs to be
rendered. As you can see, rendering the form--including potential validation
error messages--is done by adding nothing but a single element to the template.</p>
<p>``` xml
<pre><code>&lt;title&gt;Heist and digestive-functors playing nice&lt;/title&gt;
<p> </head>
<pre><code>&lt;formElm /&gt;
<p> </body>
<p>With this, we have seen how to use <em>digestive-functors</em> and Heist together in a
win-win scenario. On the one hand you mostly maintain your separation of
concerns by using Heist for most of your HTML output, while on the other hand
you can enjoy the great <em>digestive-functors</em> library as-is.</p>
Jump to Line
Something went wrong with that request. Please try again.