Created
March 30, 2012 22:00
-
-
Save nagat01/2255868 to your computer and use it in GitHub Desktop.
F# html and javascript generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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