Created
November 13, 2009 01:56
-
-
Save vito/233518 to your computer and use it in GitHub Desktop.
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
package main | |
import ("fmt"; "reflect"); | |
type Element struct { | |
name string; | |
contents []string; | |
attributes map[string]string; | |
} | |
type HTML interface { | |
Attrs(); | |
Out(); | |
} | |
type A map[string]string; | |
func element(name string, content ...) *Element { | |
ele := new(Element); | |
ele.name = name; | |
v := reflect.NewValue(content).(*reflect.StructValue); | |
ele.contents = make([]string, v.NumField()); | |
for i := 0; i < v.NumField(); i++ { | |
switch v.Field(i).Interface().(type) { | |
case string: | |
ele.contents[i] = v.Field(i).Interface().(string); | |
default: | |
ele.contents[i] = v.Field(i).Interface().(*Element).Out(); | |
} | |
} | |
ele.attributes = nil; | |
return ele; | |
} | |
func (self *Element) Out() string { | |
s := "<" + self.name; | |
for key, val := range self.attributes { | |
s += " " + key + "=\"" + val + "\""; | |
} | |
s += ">"; | |
for idx, val := range self.contents { | |
if idx > 0 { | |
s += " "; | |
} | |
s += val; | |
} | |
s += "</" + self.name + ">"; | |
return s; | |
} | |
func (self *Element) Attrs(attrs A) *Element { | |
self.attributes = attrs; | |
return self; | |
} | |
func div(content ...) *Element { | |
return element("div", content); | |
} | |
func br() Element { | |
return Element{"br", nil, nil}; | |
} | |
func main() { | |
fmt.Printf( | |
"Div: %v\n", | |
div( | |
"This is the content!", | |
"Foo!", | |
div("Bar!") | |
.Attrs(A {"class": "foo" }) | |
).Out() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment