Thursday, July 21, 2011

An awesome C# template engine

There literally isn't anything (beyond writing your own operating system level stuff .... and I sure someone did that too ;) ) that I do not see being (already) done with .NET

Want to embed a programming language .... been there done that.
Want to write a highly scale-able object / document database .... done.
Additionally there are a large number of projects that were written first in java and ported to C# (e.g. sharpssh).

And the latest case in point and the reason for this post is a template engine. The StringTemplate. (If you want to learn how to write your own engine ... even that information is available!)

For StringTemplate I suggest that you first view the Five Minute Introduction : http://www.antlr.org/wiki/display/ST/Five+minute+Introduction

And to see it in use take a look at a code project article : http://www.codeproject.com/KB/codegen/DotNetCodeGeneration.aspx

Next you should look at the cheat sheet : http://www.antlr.org/wiki/display/ST/StringTemplate+cheat+sheet

One point to note is that stringtemplate takes an innovative approach to for loops. It does this by using anonymous subtemplates.
Basically :

<attribute:{anonymous-template}>Apply an anonymous template to each element of attribute. The iterated it atribute is set automatically.
<attribute:{argument-name_ | _anonymous-template}>Apply an anonymous template to each element of attribute. Set the argument-name to the iterated value and also set it.

Looping through a hashtables and lists e.g. is covered in an example here : http://stackoverflow.com/questions/2325782/nested-loop-in-stringtemplate


And if this doesn't suit you (why wouldn't it? ... I'd like to know). Some project from here definitely will : http://csharp-source.net/open-source/template-engines
Enjoy!

1 comment:

  1. Have a look at http://razorengine.codeplex.com/

    It uses MVC's razor engine which is highly optimized, widely used and well documented. It allows for customization on a greater level than StringTemplate too.

    ReplyDelete