Created
May 23, 2012 16:03
-
-
Save einarwh/2776105 to your computer and use it in GitHub Desktop.
How to self-wrap a string in an HTML tag.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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