Advertisement
Guest User

Untitled

a guest
Nov 25th, 2015
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.98 KB | None | 0 0
  1.  
  2.  
  3. type Attribute = Attribute of string*string
  4.  
  5. type Node =
  6.     | Element of string * Node list
  7.     | Text of string
  8.     | Attributes of Attribute list
  9.     with
  10.         static member ToHTMLString node =
  11.             match node with
  12.             | Element (name, children) ->
  13.                 // Attributes nodes and child nodes are inserted at different places
  14.                 // in generated html so split 'em up
  15.                 let attributes, other = children |> List.partition (fun child ->
  16.                     match child with Attributes _ -> true | _ -> false
  17.                 )
  18.                 let attributesString =
  19.                     attributes
  20.                     |> List.map Node.ToHTMLString
  21.                     |> String.concat ""
  22.                 let bodyString =
  23.                     other
  24.                     |> List.map Node.ToHTMLString
  25.                     |> String.concat ""
  26.                 sprintf "<%s%s>%s</%s>" name attributesString bodyString name
  27.             | Attributes list ->
  28.                 List.fold (fun str (Attribute (name,value)) ->
  29.                     sprintf "%s %s='%s'" str name value  
  30.                 ) "" list
  31.             | Text text ->
  32.                 text // Todo escape
  33.  
  34. module Element =
  35.     let element name children = Element (name,children)
  36.  
  37.     let Html = element "html"
  38.     let Head = element "head"
  39.     let Title text = element "title" [(Text text)]
  40.     let Body = element "body"
  41.     let P = element "p"
  42.  
  43. [<CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
  44. module Attribute =
  45.     let attribute name value = Attribute (name,value)
  46.  
  47.     let Background = attribute "background"
  48.     let Style = attribute "style"
  49.  
  50. open Element
  51. open Attribute
  52.  
  53. let page =
  54.     Html [
  55.         Head [
  56.             Title "Page Title"
  57.         ]
  58.         Body [
  59.             Attributes [Background "black"; Style "default"]
  60.             P [Text "Some body text!!"]
  61.         ]
  62.     ]
  63.  
  64. printfn "HTML: %s" (Node.ToHTMLString page)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement