Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created May 23, 2012 16:03
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/2776105 to your computer and use it in GitHub Desktop.
Save einarwh/2776105 to your computer and use it in GitHub Desktop.
How to self-wrap a string in an HTML tag.
namespace DynamicTag
{
class Program
{
static void Main()
{
string s = "blog"
.Tag("a")
.Href("http://einarwh.posterous.com")
.Style("font-weight: bold");
Console.WriteLine(s);
Console.ReadLine();
}
}
public class Tag : DynamicObject
{
private readonly string _name;
private readonly string _content;
private readonly IDictionary<string, string> _props =
new Dictionary<string, string>();
public Tag(string name, string content)
{
_name = name;
_content = content;
}
public override bool TryInvokeMember(
InvokeMemberBinder binder,
object[] args,
out object result)
{
_props[binder.Name] = GetValue(args) ?? string.Empty;
result = this;
return true;
}
private string GetValue(object[] args)
{
if (args.Length > 0)
{
var arg = args[0] as string;
if (arg != null)
{
return arg;
}
}
return null;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("<").Append(_name);
foreach (var p in _props)
{
sb.Append(" ")
.Append(p.Key.ToLower())
.Append("=\"")
.Append(p.Value)
.Append("\"");
}
sb.Append(">")
.Append(_content)
.Append("</")
.Append(_name)
.Append(">");
return sb.ToString();
}
public static implicit operator string(Tag tag)
{
return tag.ToString();
}
}
public static class StringExtensions
{
public static dynamic Tag(this string content, string name)
{
return new Tag(name, content);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment