Late-bound Eval - email templates revisited
programming, spark, tech, templating 14 Comments »Going back to December there was a comment on Using Spark as a general purpose template engine about the use of anonymous types for your ViewData model. Or about surfacing information in general without being type-specific.
Out of curiosity. If in EmailView I just had a public property…
public object data {get; set;}
and set the data using an anonymous type like so…
view.data = new {user = new {first=”Phil”, Last=”Haack”}};
Could I do this in the template
Hi ${data.user.last}, ${data.user.first}
To which I replied
Well… Sort of… But not really…
Thinking about it later I was mulling over the steps you would take to inject small DLR expressions of something like Ruby or Python. For performance you’d want to have keep and re-use the same code instance, because it trains and optimizes itself based on the types that pass through it. Most DLR expressions are ultimately run with the same type of value at most of their code points, which is how dynamic language engines can get blisteringly fast performance out of a run-time-type situation.
Then I realized something. That’s what the dynamic keyword does! It’s a tiny instantiation of a csharp DLR expression.
Hey, wait a second! Isn’t this exactly what the C# 4.0 dynamic keyword is for?
So then the answer is yes - with C# 4.0 you’ll be able to do exactly what you were asking.
And then after thinking about it even more I realized that’s also exactly what ViewData.Eval is for. The problem with ${ViewData.Eval(”data.user.last”)} is you’re not really gaining the benefit of late binding from a wrist pain standpoint. Yes, you haven’t declared the viewdata types, but taken together the repeated ViewData.Eval( ) will increase the overall template size and reduce readability.
Enter a new syntax! Within a code expression it’s never valid to have a # in front of an identifier, or series of identifiers connected by dots. That syntax is now repurposed - when it’s seen it’s treated as the string argument for a call to Eval.
Hi ${#user.last}, ${#user.first}
Read the rest of this entry »

Recent Comments