Skip to content

Instantly share code, notes, and snippets.

@vito
Created November 13, 2009 01:56
Show Gist options
  • Save vito/233518 to your computer and use it in GitHub Desktop.
Save vito/233518 to your computer and use it in GitHub Desktop.
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