Oct 12, 2010

HTML output from a haskell

Haskell is a programming language which is capabler of creating dynamic and static web pages. Now I will explain how to create a static web page by using haskell.
First of all you may install these modules to run your program. Install these things by using cabal module installer. Module is Html. If you get errors, read those error messages and try to install other needed modules.

In the program you should
import Text.Html

This will load all the relevant html things to the program.
So now we try to write a basic html codes.

page = [
   body<< [
     p<< "First paragraph",
     p<< "First Paragraph"
    ]
   ]
main = putStrLn  $ renderHtml page

Then you must run it like this,
runhaskell filename.hs
This will print some things with html tags.

So we can modify this as we need. We can insert a title, background colour like this.

htmlPage
      = header
        << thetitle
           << "My Haskell Home Page"
   +++ body ! [bgcolor "#aaff88"] << " "

main = putStrLn $ renderHtml htmlPage

Now we can add details to this program in order  to add content into the web page. For that only you shoula modify the line "+++ body ..." to some thing like this.
+++ bopdy ![bycolor "#aaaaaa"] << bodyCon
Now this will search for "body" key word. We must add the content to that like;

bodyCon = p ! [align "center"] << "This is the content of body tag"

You can add more thing to the body of your html page. So we can try,

bodyCon = p ! [align "center"] << "This is the body of the html page"
          +++ p << "second p tag"
          +++ table ! [border 2]<< tableCon

tableCon = (col1_r1 `above` col1_r2) `beside` (col2_r1 `above`col2_r2)
   where
        col1_r1 = td << "col1 r1"
        col1_r2 = td << "col1 r2"
        col2_r1 = td << "col2_r1"
        col2_r2 = td << "col2_r2"

You can see in this coding I had use two p tags and one table. Likewise we can create hole html page from this.

Up to this point we can get a html output to the screen. But we need to create a html page without printing this to the stdout.
So to do that we must modify the main in the coding to this.

main = writeFile "haskell.htm" (renderHtml htmlPage)

Now this will create a html file in the working directory. You can view  it by using a web browser.
You can make this page dynamic by adding more functions to create dynamic content.

No comments:

Post a Comment

Your comments are always welcome ...