Skip to content

Instantly share code, notes, and snippets.

@back2dos
Created March 12, 2012 11:08
Show Gist options
  • Save back2dos/2021229 to your computer and use it in GitHub Desktop.
Save back2dos/2021229 to your computer and use it in GitHub Desktop.
Fluent tag interface for haxe
package ;
using Tag;
class Main
{
static function main()
{
var t = "div".tag().att("id", "container")
.child("a".tag().att("href", "http://www.haxe.org")
.child("img".tag().att("src", "/images/logo.png")))
.child("a".tag().att("href", "http://www.haxe.org/api")
.child("API Reference"));
trace(t.toString());
}
}
package ;
typedef Node = {
function toString():String;
}
class Tag {
var name:String;
var attrs:Array<{name:String, value:String}>;
var children:Array<Node>;
function new(name) {
this.attrs = [];
this.name = name;
this.children = [];
}
public function att(name:String, value:String) {
attrs.push({name:name, value:value});
return this;
}
public function child(child:Node) {
children.push(child);
return this;
}
public function toString() {
var strBuf = new StringBuf();
strBuf.add("<" +name);
for (a in attrs)
strBuf.add(" " +a.name + '="' +a.value + '"');
if (children.length == 0)
strBuf.add("/>");
else
{
strBuf.add(">");
for (c in children)
strBuf.add(c.toString());
strBuf.add("</" + name + ">");
}
return strBuf.toString();
}
static public function tag(name:String):Tag
return new Tag(name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment