HtmlBuilder

HtmlBuilder could help us to build html intuitionistic:

HtmlBuilder hb = HtmlBuilder.New
.table
    .tr
        .td
            .text("test")
        .end
    .end
.end;
string html = hb.ToString();

Now, the string html will be:

<table><tr><td>test</td></tr></table>

The "text" will do html encode before it be added, so we don't need to worry about it by ourselves.

And, if we use more or less "end", it will raise an exception.

If there is nothing between start tag and end tag, it will generate a short closed tag:

HtmlBuilder hb = HtmlBuilder.New.ul.li.end.end;

The result will be:

<ul><li /></ul>

To build a hyper link is like following:

HtmlBuilder.New.a("http://llf.javaeye.com").text("myblog").end.ToString();

The generated html snippet is:

<a href="http://llf.javaeye.com">myblog</a>

We can include another HtmlBuilder as inner html too:

HtmlBuilder b = HtmlBuilder.New.a("t.aspx").text("tt").end;
HtmlBuilder b2 = HtmlBuilder.New.li.include(b).end;
string html = b2.ToString();

The string html will be:

<li><a href="t.aspx">tt</a></li>

Add "class" to a tag:

HtmlBuilder b = HtmlBuilder.New.li.Class("nt").text("tt").end;

The result will be:

<li class="nt">tt</li>

HtmlBuilder only supoort few html tags and attributes. To support more tag and attribute should use "tag" and "attr" function:

HtmlBuilder hb = HtmlBuilder.New
.table
    .tr.attr("width", "100%")
        .td.attr("rowspan", "2")
            .tag("b").Class("red")
            	.text("test")
            .end
        .end
    .end
.end;

The result will be:

<table><tr width="100%"><td rowspan="2"><b class="red">test</b></td></tr></table>

Have fun!

Last edited Apr 9, 2014 at 3:35 PM by lifeng, version 10

Comments

shootsoft Jun 17, 2009 at 6:48 AM 
Great!