by thorhalvor

Are you still writing your own TemplateEngine?

Years ago I was on a project that needed a dynamic engine for writing documents based on a template. It had to be possible to add keys like “$name$” in a text and the engines job was to replace with a Name from a given context. I ended up writing a module that used reflection on my context-object and it worked the way I wanted. – But it took some hours developing it…

NVelocity / TemplateEngine

Later I discovered NVelocity. NVelocity is an open source project, and as many others starting with a ‘N’, is based on the Java project Velocity. Castle Projects has abstracted the templating process and made it even easier to use in their TemplateEngine Component. This component gave me all I wanted and more. If I just had knew earlier..

An example of a template for Castle’s TemplateEngine is given below:

Hi $customer.FirstName,
your account has been lost..
We are sorry for that!

Regards,
The bank

The code below is reading the template, mapping the key-properties and writing the output the the variable ‘text’. As you can see, it is putting the Customer object into an Hashtable with keyword “customer” and then forwarding it to the Processor as context. More or less the same I did in “my own engine”.

string text;
var customer = GetCustomer();
using (var writer = new StringWriter())
{
    var context = new Hashtable();
    context.Add("customer", customer);
    TemplateEngine.Process(context, "yourtemplatefilename.txt", writer);
    text = writer.ToString();
}

You can also do if/else and foreach logic (see here for more examples):

#foreach($person in $people)
<table>
       <tr>
           <th>Name</th>
           <th>Age</th>
    </tr>
</table>
#end

And:

#if($order.Status == "Undefined")
  Sorry, but we don't know this order.
#elseif($order.Status == "Created")
  Your order is being processed. Hold on!
#end
RazorEngine

Most new web projects created in the “.NET World” today, at least the one I know of, is based on ASP.NET MVC 3 and the parsing technology Razor. Developers have learned to use and to like the Razor syntax. And what could be better for a new templateengine than using the same technology? Matthew Abbot has done something about this and made in late 2010 the first version of the Razor Template Engine, in v2.0 called RazorEngine. It is opensource and can be found on GitHub and as a nugetpackage, ‘Install-Package RazorEngine’.

Simple example:

var template = "Hi @Model.FirstName! Knock knock who's there?";
var result = Razor.Parse(template, new { FirstName = "KenSentMe" });

or you could offcourse read the template from a file:

var template = File.ReadAllText("yourfilename.txt");

 

A nice feature is that the template-engine support anonymous types, – as you can see in the second parameter of Razor.Parse(). (and also DynamicObject and ExpandoObject). With this loose coupling to the context/model it makes it easier for a developer to extend it. He can now just add a new property directly instead of creating a specific class just to works as a “placeholder”.

I guess there are many more template engines “out there” but these are the two I have used on my last projects. I use RazorEngine on my current project, with html-email-templates, and it works very well. The main reason I choose RazorEngine is mostly because we use MVC 3 and Razor on the websites and the email template is based on the same style and context(Viewmodels). But also the fact that it is so easily downloaded and upgraded through the NuGet Package.

So If you still write your own templateengines I hope you will take a look on one of these engines next time.