Created
July 25, 2009 06:08
-
-
Save JakeWharton/154713 to your computer and use it in GitHub Desktop.
Rudimentary implementation of pyy_tag/html_tag in C#
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
using System; | |
using System.Text; | |
using System.Reflection; | |
namespace pyysharp | |
{ | |
public abstract class HtmlTag | |
{ | |
private static string TAB = " "; | |
public object[] Children; | |
public string[] Arguments; | |
public bool DoInline = false; | |
public bool IsSingle = false; | |
public bool IsPretty = false; | |
public HtmlTag(params object[] Arguments) | |
{ | |
this.Children = Arguments; | |
} | |
public string Render() | |
{ | |
return this.Render(1, false); | |
} | |
public string Render(int Indent, bool IsInline) | |
{ | |
StringBuilder Rendered = new StringBuilder("<"); | |
IsInline = this.DoInline | IsInline; | |
string Name; | |
if (this.GetType().Name[0] == '_') | |
Name = this.GetType().Name.Substring(1); | |
else | |
Name = this.GetType().Name; | |
Rendered.Append(Name); | |
foreach (string Arg in this.Arguments) | |
{ | |
PropertyInfo f = this.GetType().GetProperty(Arg, BindingFlags.Public | BindingFlags.Instance); | |
try | |
{ | |
object Value = f.GetValue(this, null); | |
Rendered.Append(string.Format(" {0}=\"{1}\"", Arg, Value.ToString())); | |
} | |
catch (NullReferenceException) | |
{ | |
} | |
} | |
if (this.IsSingle && this.Children.Length == 0) | |
{ | |
Rendered.Append(" />"); | |
} | |
else | |
{ | |
Rendered.Append(">"); | |
Rendered.Append(this.RenderChildren(Indent, IsInline)); | |
bool NoChildren = this.IsPretty && (this.Children.Length > 0) | |
&& (!(this.Children.Length == 1 && this.Children[0] is HtmlTag)); | |
if (NoChildren && !IsInline) | |
{ | |
Rendered.Append('\n'); | |
Rendered.Append(HtmlTag.TAB, 0, Indent - 1); | |
} | |
Rendered.Append(string.Format("</{0}>", Name)); | |
} | |
return Rendered.ToString(); | |
} | |
private string RenderChildren(int Indent, bool IsInline) | |
{ | |
StringBuilder Rendered = new StringBuilder(); | |
foreach (object Child in this.Children) | |
{ | |
if (Child is HtmlTag) | |
{ | |
HtmlTag HtmlChild = (HtmlTag)Child; | |
if (!IsInline && HtmlChild.IsPretty) | |
{ | |
Rendered.Append('\n'); | |
Rendered.Append(HtmlTag.TAB, 0, Indent); | |
} | |
Rendered.Append(HtmlChild.Render(Indent + 1, IsInline)); | |
} | |
else | |
{ | |
Rendered.Append(Child.ToString()); | |
} | |
} | |
return Rendered.ToString(); | |
} | |
public override string ToString() | |
{ | |
return this.Render(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment