Skip to content

Instantly share code, notes, and snippets.

@hesselbom
Created March 12, 2012 10:55
Show Gist options
  • Save hesselbom/2021150 to your computer and use it in GitHub Desktop.
Save hesselbom/2021150 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")));
trace(t.toString());
}
}
package ;
typedef TagValue =
{
name:String,
attrs:Array<{name:String, value:String}>,
children:Array<TagValue>
}
class Tag
{
static public function tag(name:String):TagValue
return {name:name, attrs:[], children:[]}
static public function att(tag:TagValue, name:String, value:String)
{
tag.attrs.push({name:name, value:value});
return tag;
}
static public function child(tag:TagValue, child:TagValue)
{
tag.children.push(child);
return tag;
}
static public function toString(tag:TagValue)
{
var strBuf = new StringBuf();
strBuf.add("<" +tag.name);
Lambda.iter(tag.attrs, function(attr) strBuf.add(" " +attr.name + '="' +attr.value + '"'));
if (tag.children.length == 0)
strBuf.add("/>");
else
{
strBuf.add(">");
Lambda.iter(tag.children, function(child) strBuf.add(toString(child)));
strBuf.add("</" +tag.name + ">");
}
return strBuf.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment