[Journal - Templated Text Generation, Simplified]

Templated Text Generation, Simplified

Wednesday, February 1, 2006

In recent posts, I have introduced the text generation facilities in the Gregor.Core library. These are quite a complex beast: an entire graph of objects is used as input for the text generation, and that graph being shaped by path information contained in an XML document, with further assistance by a code interpreter (like .NET Console).

Now, what if you have a simple data class with any number of properties returning data that's ready for output? With a simple template, an app should not need to build an object graph.

The solution is calling Parse.ProcessTemplate(), passing an object that implements IEvaluator in such a way that template parameters are interpreted as property names:

// the data
string sTitle = "Templated Text Generation, Simplified";
ArticleInfo article = new Article(sTitle);

// the template
string sTemplate = "<h1>$Title%</h1>";

// replace template parameters
IEvaluator evaluator = new CReflectingEvaluator(article);
string sText = Parse.ProcessTemplate(evaluator, sTemplate);

CReflectingEvaluator allows passing a System.Type object as well, so that static properties of that type are evaluated.