Tag Builder

Class Library
C#
GitHub Gist

What It Is

A C# class for creating HTML tags and structures in code

Status

I haven’t used it much, honestly. The goal was to provide a way to return small snippets of HTML (for use with something like HTMX) without having to have a separate template. I think I’ll use it in the future.

(I realized there’s a similar class built into Nemmet. I need to consolidate these at some point. There’s a lot of overlap between these two libraries.)

Details

A simple class that allows you to create HTML tags from C# much like the XElement class. You can nest them in constructors, and assign names, IDs, and classes using an Emmet-style shorthand.

Tag automatically converts to string. Passing it as a string will do the same thing as calling ToString() on it.

Basic usage:

var tag = new Tag("p");
var html = tag.ToString();
// html will equal "<p></p>"

var tag = new Tag("p", "Deane was here");
// <p>Deane was here</p>

var tag = new Tag("p#lede", "Deane was here");
// <p id="lede">Deane was here</a>

var tag = new Tag("p#lede.small-caps", "Deane was here");
// <p id="lede" class="small-caps">Deane was here</a>

You can nest tags in the constructor (theoretically infinitely).

var tag = new Tag("p", "Deane was here", new Tag("br"));
// <p>Deane was here<br/></a>

var tag = new Tag("p",
  new Tag("ul",
    children.Select(c => new Tag("li", c)
  )
)
// <p><ul><li>Alec</li><li>Gabby</li><li>Bells</li></ul></p>

It’s fluent-ish…

var tag = new Tag("p")
  .SetContent("Deane was here")
  .AddStyle("display", "none")
  .AddClass("foo")
  .AddClass("bar")
// <p class="foo bar" style="display:none;">Deane was here</p>

var tag = new Tag("img")
  .SetAttribute("src", "/image.jpg")
// <img src="/image.jpg" />

I tend to subclass this for common tags. Since the tag name is now known, the “tag spec” becomes less important and can be optional.

public class Link : Tag
{
  public Link(string text, string url, string spec = null) : base(spec, text)
  {
    Name = "a";
    SetAttribute("href", url);
  }
}

var link = new Link("Home", "/");
var link = new Link("Home", "/", ".home-link");