[stringtemplate-interest] [Patch] CustomFormatAttribute
lists.stringtemplate at jhoward.fastmail.fm
lists.stringtemplate at jhoward.fastmail.fm
Thu Aug 23 18:19:35 PDT 2007
I wanted to be able to have the model tell the view how it should be
rendered, without creating a separate class for each different way of
rendering a float/date/etc. Here's the goal:
----
[CustomFormat("0.0%")]
public double A1 {
get { return a1_; }
set { a1_ = value; }
}
----
That's C# of course. The bit in '[]' is a .Net "Attribute" (nothing to
do with the ST concept of "Attribute"!). The equivalent in Java is the
"Annotation". The "0.0%" is a standard .Net format string, passed to
IFormattable.Format(). All of the standard .Net base types support
IFormattable, and you can easily add this interface to your own types
too (it only has one member).
So, here's all the code necessary to get it to work:
ASTExpr.cs:
----
In ASTExpr.GetPropertyValue() after:
@value = pi.GetValue(paramBag.instance, null);
insert:
object[] custAttr = pi.GetCustomAttributes(
typeof(CustomFormatAttribute), false);
if (custAttr.Length>0) {
CustomFormatAttribute attr =
(CustomFormatAttribute) custAttr[0];
string fmt = attr.Format;
IFormattable f = (IFormattable) @value;
@value = f.ToString(fmt, null);
}
----
And then add a test:
----
class CustomFormatTest {
double a1_, a2_;
public CustomFormatTest(double a1, double a2) {
a1_ = a1;
a2_ = a2;
}
[CustomFormat("0.0%")] public double A1 {
get { return a1_; } set { a1_ = value; } }
public double A2 {
get { return a2_; } set { a2_ = value; } }
}
[Test] public void CustomFormatAttributeTest() {
StringTemplate st = new StringTemplate(
"$Items:{<td>$it.A1$</td><td>$it.A2$</td>}$");
List<CustomFormatTest> l = new List<CustomFormatTest>();
l.Add(new CustomFormatTest(.5, .6));
st.SetAttribute("Items", l);
Assert.AreEqual("<td>50.0%</td><td>0.6</td>", st.ToString());
}
----
That's it! This seems to fit within the MVC separation rules quite
nicely - does it seem like a reasonable addition to ST?
TIA,
Jeremy
--
Jeremy Howard
jhoward at optimaldecisions.com
The Optimal Decisions Group, Pty Ltd
More information about the stringtemplate-interest
mailing list