Reputation: 916
I'm using snap framework and haskell to create simple web application.I want to know How can I render a list to web page,It is like this I have a list with first name and last name
[["firstName1","lastName1"],["firstName2","lastName2"],["firstName3","lastName3"]]
I want to display these information in two columns,What are the possible ways to do this,I was able to bind single value information and display on webpage.
Upvotes: 1
Views: 710
Reputation: 7272
Don's suggestion of blaze-html is one way to do it, but I find that when I do it that way I have more of a tendency to violate the commonly used MVC design pattern by embedding the view (in this case the HTML) into your Haskell code. In some cases if you're just trying to do something quick and dirty this may be the thing to do. But if you want this to fit into a larger application in a way that separates the view from the controller and allows designers to work with it who are unfamiliar with Haskell, then you might be better off using the Heist template system.
We have a Heist tutorial here. I also recently wrote a series of blog posts about just this sort of thing. The second post in the series in particular is probably the most relevant to your question. Here's some code that does something like what you want:
names :: [(Text,Text)]
names = [("Alice", "Anderson"), ("Bob", "Brown")]
nameSplice :: (Text, Text) -> Splice Application
nameSplice name =
runChildrenWithText [("firstName", fst name), ("lastName", snd name)]
namesSplice :: Splice Application
namesSplice = mapSplices nameSplice names
After you bind the names splice somewhere in your application with bindSplice "names" namesSplice
you can get at this data from a template like this:
<table>
<names>
<tr><td><firstName/></td><td><lastName/></td></tr>
</names>
</table>
The nice thing about this is that the web designer has complete control over how the names are displayed. If they needed to change the display to say an unordered list in the format "lastname, firstname" that would be very easy to do here without needing to recompile your application.
Upvotes: 6
Reputation: 137957
I have a strong preference for blaze-html, as an excellent set of combinators for quickly translating structured Haskell data types into html.
It has a nice home with lots of examples, like so:
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding (head)
import Control.Monad
import Text.Blaze.Html4.Strict
import Text.Blaze.Renderer.Text
import qualified Data.Text.Lazy.IO as T
main = T.writeFile "f" (renderHtml (draw xs))
where
xs = [("firstName1","lastName1"),("firstName2","lastName2"),("firstName3","lastName3")]
draw xs = html $ do
head $ title "Example"
body $ do
h1 "Heading"
table $ forM_ xs $ \(f,l) ->
tr $ do
td f
td f
Generates a text
string containing this table:
Heading
firstName1 firstName1
firstName2 firstName2
firstName3 firstName3
If you can output text
from snap, you should be good.
Upvotes: 4