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 (1_simple.st):
//1_simple.st
SELECT $column$ FROM $table$;
Template Anonymous Type:

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

//2_simpleObjects.st
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");
   4:  
   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:

//3_simpleLoop.st
$items: {num1|
    <li>$num1$</li>
    }$
$end$

and bind the list using this code:

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

Conclusion:

  • 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.
 

Shani Raba

Juggling between Performance Optimization, Agile Training, Continuous Delivery, Get Things Done. Role: Group Leader. Moto: Love your coders.

 

One thought on “StringTemplate Introduction

Comments are closed.