Using HSP

To enable HSP support, you must install the happstack-hsp package.

HSP is an XML-based templating system that allows you to embed XML in your Haskell source files. If you have ever had to use PHP, you may want to run screaming from this idea. However, the HSP solution is far saner than the PHP solution, so you may want to give it a chance. The first thing we will see is a funny `OPTIONS_GHC` pragma at the top of our file:
> {-# LANGUAGE FlexibleContexts, OverlappingInstances #-} > {-# OPTIONS_GHC -F -pgmFtrhsx #-} > module Main where >
HSP works by running the code through an external pre-processor named `trhsx`. This pragma at the top is how we tell GHC that this file needs to be run through the `trhsx` pre-processor in order to work. Next we have some imports:
> import Control.Applicative ((<$>)) > import Control.Monad.Identity (Identity(runIdentity)) > import qualified HSX.XMLGenerator as HSX > import Happstack.Server.HSP.HTML > import Happstack.Server (Request(rqMethod), ServerPartT, askRq, nullConf, simpleHTTP) > import HSP.Identity () -- instance (XMLGen Identity) >
Now we can define a function which generates an HTML page:
> hello :: ServerPartT IO XML > hello = unXMLGenT > > > Hello, HSP! > > >

Hello HSP!

>

We can insert Haskell expression such as this: <% sum [1 .. (10 :: Int)] %>

>

We can use the ServerPartT monad too. Your request method was: <% getMethod %>

>
>

We don't have to escape & or >. Isn't that nice?

>

If we want <% "<" %> then we have to do something funny.

>

But we don't have to worry about escaping <% "

a string like this

" %>

>

We can also nest <% like <% "this." %> %>

> > > where > getMethod :: XMLGenT (ServerPartT IO) String > getMethod = show . rqMethod <$> askRq > > main :: IO () > main = simpleHTTP nullConf $ hello >
The first thing we notice is that syntax looks pretty much like normal HTML syntax. There are a few key differences though: 1. like XML, all tags must be closed 2. like XML, we can use shortags (e.g. < hr />) 3. We do not have to escape & and > 4. To embed < we have to do something extra funny The syntax:
<% haskell expression %>
allows us to embed a Haskell expression inside of literal XML. As shown in this line:
#ifdef HsColour >

We can also nest <% like <% "this." %> %>

#endif
we can freely nest Haskell and XML expressions.

What does trhsx do?

In order to use HSP it is very useful to understand what is actually going on behind the magic. If we have the line:
#ifdef HsColour > foo :: XMLGenT (ServerPartT IO) XML > foo = foo #endif
and we run `trhsx`, it gets turned into a line like this:
> foo :: XMLGenT (ServerPartT IO) XML > foo = genElement (Nothing, "span") [ asAttr ("class" := "bar") ] [asChild ("foo")] >
We see that the XML syntax has simply been translated into normal haskell function calls.

Important HSX types and classes

There are a few types and classes that you will need to be familiar with.

the XMLGenT type

The first type is the `XMLGenT` monad transformer:
#ifdef HsColour > newtype XMLGenT m a = XMLGenT (m a) > -- | un-lift. > unXMLGenT :: XMLGenT m a -> m a > unXMLGenT (XMLGenT ma) = ma #endif
This seemingly useless type exists solely to make the type-checker happy. Without it we would need an instance like:
#ifdef HsColour > instance (EmbedAsChild (IdentityT m) a, Functor m, Monad m, m ~ n) => > EmbedAsChild (IdentityT m) (n a) where > asChild = ... #endif
Unfortunately, because `(n a)` is so vague, that results in overlapping instances that cannot be resolved without `IncohorentInstances`. And, in my experience, enabling `IncohorentInstances` is *never* the right solution. So, when generating XML you will generally need to apply `unXMLGenT` to the result to remove the `XMLGenT` wrapper as we did in the `hello` function. Anyone who can figure out to do away with the `XMLGenT` class will be my personal hero.

the XMLGen class

Next we have the `XMLGen` class:
#ifdef HsColour > class Monad m => XMLGen m where > type XML m > data Child m > data Attribute m > genElement :: Name -> [XMLGenT m [Attribute m]] -> [XMLGenT m [Child m]] -> XMLGenT m (XML m) > genEElement :: Name -> [XMLGenT m [Attribute m]] -> XMLGenT m (XML m) > genEElement n ats = genElement n ats [] > xmlToChild :: XML m -> Child m > pcdataToChild :: String -> Child m #endif
Most of these functions and types are used internally and not used directly by the developer. You will notice that we have a type-class instead of just simple functions and types. One feature of HSX is that it is not tied to any particular XML representation. Instead, the XML representation is based on the monad we are currently inside. For example, inside of a javascript monad, we might generate javascript code that renders the XML, inside of another monad, we might generate the `Node` type used by the `heist` template library. We will see some examples of this in a later section. The `data` and `type` declarations appearing inside the class declaration are allowed because of the `TypeFamalies` extension. For a detailed coverage of type famalies see this wiki entry.

the XML m type synonym

The `XMLGen` type-class defines an associated type synonym `XML m`:
#ifdef HsColour > type XML m #endif
`XML m` is a synoynm for whatever the xml type is for the monad `m`. We can write an XML fragment that is parameterized over an arbitrary monad and xml type like this:
> bar :: (XMLGenerator m) => XMLGenT m (HSX.XML m) > bar = bar >
Note that we had this qualified import:
#ifdef HsColour > import qualified HSX.XMLGenerator as HSX #endif
That is because we need to differentiate the `XML` associated type synonym from the plain-old `XML` data type that is declared elsewhere. Having two types with the same name is a bit silly, but that is the way it is for now.

the EmbedAsChild class

The `EmbedAsChild` is used to turn a value into a list of children of an element:
#ifdef HsColour > type GenChildList m = XMLGenT m [Child m] > > -- | Embed values as child nodes of an XML element. The parent type will be clear > -- from the context so it is not mentioned. > class XMLGen m => EmbedAsChild m c where > asChild :: c -> GenChildList m #endif
There are generally many instances of `EmbedAsChild` allowing you to embed `String`, `Text`, `Int`, and other values. You might find it useful to create additional instances for types in your program. We will some some examples later in this tutorial. To use the `EmbedAsChild` class we us the `<% %>` syntax shown earlier. For example, when we write:
> a :: (XMLGenerator m) => GenChildList m > a = <% 'a' %> >
It gets turned into:
#ifdef HsColour > a :: (XMLGenerator m) => GenChildList m > a = (asChild ('a')) > #endif

the EmbedAsAttr class

The `EmbedAsAttr` class is similar to the `EmbedAsChild` class. It is used to turn arbitrary values into element attributes.
#ifdef HsColour > type GenAttributeList m = XMLGenT m [Attribute m] > > -- | Similarly embed values as attributes of an XML element. > class XMLGen m => EmbedAsAttr m a where > asAttr :: a -> GenAttributeList m #endif
If we have some attributes like this:
#ifdef HsColour > foo = foo #endif
It will get translated to:
#ifdef HsColour > foo > = (genElement (Nothing, "span") > [asAttr ("class" := "foo"), asAttr ("size" := (80 :: Int)), > asAttr ("bogus" := False)] > [asChild ("foo")]) #endif
which might be rendered as:
<span class="foo" size="80" bogus="false" >foo</span >

the XMLGenerator class

You may have noticed that some of the examples had a class constraint `(XMLGenerator m)`:
#ifdef HsColour > bar :: (XMLGenerator m) => XMLGenT m (HSX.XML m) > bar = bar > #endif
`XMLGenerator` is just a class alias. It is defined as such:
#ifdef HsColour > class ( XMLGen m > , SetAttr m (HSX.XML m) > , AppendChild m (HSX.XML m) > , EmbedAsChild m (HSX.XML m) > , EmbedAsChild m [HSX.XML m] > , EmbedAsChild m String > , EmbedAsChild m Char > , EmbedAsAttr m (Attr String String) > , EmbedAsAttr m (Attr String Int) > , EmbedAsAttr m (Attr String Bool) > ) => XMLGenerator m #endif
It contains a list of common instances that all xml generation monads are expected to provide. It just saves you from having to list all thoses instances by hand when you use them.

HSX by Example

First we have a simple function to render the pages and print them to stdout:
> printXML :: Identity XML -> IO () > printXML = putStrLn . renderAsHTML . runIdentity

HSX and do syntax

It is possible to use hsx markup inside a `do`-block. You just need to be aware of one little catch. In this example:
#ifdef HsColour > doBlock :: (XMLGenerator m) => XMLGenT m (HSX.XML m) > doBlock = > do
>

A child element

>
#endif
Notice that we indent the closing </div> tag. That indentation rule is consistent with the specification for how do-notation works. It is intend for the same reason that `if .. then .. else ..' blocks have to be idented in a special way inside `do`-blocks.

defaultTemplate

There is a bit of boiler plate that appears in ever html document such as the <html>, <head>, <title>, and <body> tags. The `defaultTemplate` function provides a minial skeleton template with those tags:
#ifdef HsColour > defaultTemplate :: ( XMLGenerator m > , EmbedAsChild m body > , EmbedAsChild m headers > ) => > String -- string to put in > -> headers -- additional elements to put in <head> > -> body -- elements to put <body> > -> m (HSX.XML m) #endif </div> <h4>How to embed empty/nothing/zero</h4> `defaultTemplate` requires that we pass in `headers` and a `body`. But what if we don't have any headers that we want to add? Most `XMLGenerator` monads provide an `EmbedAsChild m ()` instance, such as this one: <div class="code"> #ifdef HsColour > instance EmbedAsChild Identity () where > asChild () = return [] #endif </div> So, we can just pass in `()` like so: <div class="code"> > empty = printXML $ defaultTemplate "empty" () () </div> Which will render as such: <div class="code"> <pre> <html ><head ><title >empty</title ></head ><body ></body ></html > </pre> </div> <h4>Creating a list of children</h4> Sometimes we want to create a number of children elements without knowing what their parent element will be. We can do that using the: <div class="code"> <%> ... </%> </div> syntax. For example, here we return two paragraphs: <div class="code"> > twoParagraphs :: (XMLGenerator m) => XMLGenT m [HSX.Child m] > twoParagraphs = > <%> > <p>Paragraph one</p> > <p>Paragraph two</p> > </%> </div> We can embed those in parent element like this: <div class="code"> > twoParagraphsWithParent :: (XMLGenerator m) => XMLGenT m (HSX.XML m) > twoParagraphsWithParent = > <div> > <% twoParagraphs %> > </div> </div> <h4><code>if .. then .. else .. </code></h4> Using an `if .. then .. else ..` is straight-foward. But what happens when you don't really want an `else` case? This is another place we can use `()`: <div class="code"> > ifThen bool = > printXML $ defaultTemplate "ifThen" () $ > <div> > <% if bool > then <% > <p>Showing this thing.</p> > %> > else <% () %> > %> > </div> > </div> <h4>Lists of attributes & optional attributes</h4> Normally attributes are added to an element using the normal html attribute syntax. HSX, has a special extension where the last attribute can be a Haskell expression which returns a list of attributes to add to the element. For example: <div class="code"> > attrList = > printXML $ defaultTemplate "attrList" () $ > <div id="somediv" ["class" := "classy", "title" := "untitled"] > > </div> > </div> The type of the elements of the list can be anything with an `EmbedAsAttr m a` instance. In this case we create a list of `Attr` values: <div class="code"> #ifdef HsColour > data Attr n a = n := a #endif </div> We can use this feature to conditionally add attributes using a simple `if .. then .. else ..` statment: <div class="code"> > optAttrList bool = > printXML $ defaultTemplate "attrList" () $ > <div id="somediv" (if bool then ["class" := "classy", "title" := "untitled"] else []) > > </div> > </div> <h3>web-routes</h3> <h3>digestive-functors</h3>