Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created February 27, 2013 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einarwh/5052379 to your computer and use it in GitHub Desktop.
Save einarwh/5052379 to your computer and use it in GitHub Desktop.
Implementation of HtmlWriter for the HTML DSL using using.
class Program
{
static void Main(string[] args)
{
new HtmlWriter(Console.Out).Write();
}
}
class HtmlWriter : BaseHtmlWriter
{
public HtmlWriter(TextWriter tw) : base(tw) {}
public override void Write()
{
using(Html())
{
using (Head())
{
using (Title())
{
Text("Greeting");
}
}
using (Body(Bgcolor("pink")))
{
using(P(Style("font-size:large")))
{
Text("Hello world!");
}
}
}
}
}
class DisposableWriter : IDisposable
{
private readonly Stack<string> _tags = new Stack<string>();
private readonly TextWriter _;
public DisposableWriter(TextWriter tw)
{
_ = tw;
}
public IDisposable Tag(string tag, params string[] attrs)
{
string s = attrs.Length > 0 ? tag + " " + string.Join(" ", attrs) : tag;
Write("<" + s + ">");
_tags.Push(tag);
return this;
}
public void Text(string s)
{
Write(s);
}
private void Write(string s) {
_.WriteLine();
}
public void Dispose()
{
var tag = _tags.Pop();
Write("</" + tag + ">");
}
}
abstract class BaseHtmlWriter
{
private readonly DisposableWriter _;
protected BaseHtmlWriter(TextWriter tw)
{
_ = new DisposableWriter(tw);
}
protected IDisposable Html()
{
return _.Tag("html");
}
protected IDisposable Body(params string[] attrs)
{
return _.Tag("body", attrs);
}
// More tags...
protected string Bgcolor(string value)
{
return Attr("bgcolor", value);
}
protected string Style(string value)
{
return Attr("style", value);
}
// More attributes...
protected string Attr(string key, string value)
{
return key + "=\"" + value + "\"";
}
protected void Text(string s)
{
_.Text(s);
}
public abstract void Write();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment