- Blogging about Cultivating a Culture, Agile Training, Continuous Delivery, Performance Optimization and Get Things Done

StringTemplate Introduction

For more background about when we use this API you can read my last post about Rendering Objects to Html

Simple Rendering of query:

   1: var query = new StringTemplate("SELECT $column$ FROM $table$;");
   2: query.SetAttribute("column", "name");
   3: query.SetAttribute("table", "User");
   4: var data = query.ToString();
We will refactor this sample to handle the queries from an outside source:
   1: var group = new StringTemplateGroup("SimpleTemplates",@"C:\Templates\TemplateEngineTestCase");
   2: var query = group.GetInstanceOf("1_simple");
   3: query.SetAttribute("column", "name");
   4: query.SetAttribute("table", "User");
   5: var data = query.ToString();
Rows 1,2 – loading the template data from a source file.
Here is the Template (
SELECT $column$ FROM $table$;
Template Anonymous Type:

In the last template usage ( We bind the parameters using strings only. but we also have a better options: let’s assume we wrote down such template:

Full Name: $Person.FirstName$ - $Person.LastName$

But let’s assume that we don’t have the Person class\instance, we can simply write it using the anonymous types:

   1: var user = new {FirstName = "Shani", LastName = "Raba"};
   2: var group = new StringTemplateGroup("OOTempaltes", @"C:\Templates\TemplateEngineTestCase");
   3: var query = group.GetInstanceOf("2_simpleObjects");
   5: query.SetAttribute("Person", user);
You can also use this kind of bindings for setting template-attributes from each one of the Person sub-classes.
Template list:

Till now it is all pretty simple to implement by yourself, but the real issue here is the List binding feature.
You can write such template:

$items: {num1|

and bind the list using this code:

   1: var templateFolder = new StringTemplateGroup("SimpleLoopTemplates", @"C:\Tempaltes\TemplateEngineTestCase");
   2: var template = templateFolder.GetInstanceOf("3_simpleLoop");
   4: template.SetAttribute("items", new List<string> {"Shani", "Doron", "Nati", "Yossi"});


  • The code is pretty simple, the templates engine implements good functionality and is well documented.
  • The StringTemplate syntax is easy to learn and well documented.
  • I still don’t like it when I need to learn a new language\syntax – it will sharpen the newbie’s curve.
  • StringTemplate is missing good Object2Template Designer.