Skip to content

Instantly share code, notes, and snippets.

@nagat01
Created March 30, 2012 22:00
Show Gist options
  • Save nagat01/2255868 to your computer and use it in GitHub Desktop.
Save nagat01/2255868 to your computer and use it in GitHub Desktop.
F# html and javascript generator
open System
type Html =
| Tag of string * Html list
| Attribute of string * string
| Content of string
override __.ToString() =
match __ with
| Tag (tag,htmls) ->
let mutable attributes = ""
let mutable innerHtml = ""
for html in htmls do
let str = string html
match html with
| Attribute (key,value) ->
attributes <- sprintf "%s %s" attributes str
| _ ->
innerHtml <- sprintf "%s\n%s" innerHtml str
sprintf "<%s%s>%s\n</%s>" tag attributes innerHtml tag
| Attribute(key,value) -> sprintf @"%s=""%s""" key value
| Content content -> content
let tag tag htmls = Tag(tag,htmls)
let html = tag "html"
let body = tag "body"
let head = tag "head"
let h1 = tag "h1"
let p = tag "p"
let attr key value = Attribute(key,value)
let id = attr "id"
let typ = attr "type"
let (=<) tag content = tag [Content content]
let (-<) tag html htmls = tag (html::htmls)
let s str = Content str
let script =
tag "script" -< typ "text/javascript"
module Doc =
let write str =
(string str).Replace("<",@"""<").Replace(">",@">""")
|> sprintf @"document.write(%s);"
let byId id =
sprintf @"document.getElementById(""%s"")" id
let writeFile file html =
let html = string html
IO.File.WriteAllText(file,html)
Diagnostics.Process.Start(@"C:\chrome.lnk",file)
|> ignore
let fn0 name body =
sprintf "function %s(){\n%s;}\n" name body
html [
head [
script [
fn0 "displayDate" <| Doc.byId "demo" + ".innerHtml=Date()"
]
]
body [
h1 =< "My First Web Page"
p [
id "demo"
s"aiueo"
]
script =< Doc.write (p =< "+ Date() +")
script =< Doc.byId "demo" + ".innerHTML=Date()"
]
]
|> writeFile @"C:\fsharp\clorets\pages\index.html"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment