Resources
- StringTemplate C# Releases / StringTemplate 4 .NET (Direct Download)
- StringTemplate 4 Language Support for Visual Studio 2010 (optional)
- Syntax Cheat Sheet (optional)
- Antlr3.Runtime.dll
- Antlr4.StringTemplate.dll
Returns template output.
using System;
using System.IO;
using Antlr4.StringTemplate;
public namespace YourNamespace
{
public class Tester
{
public string HelloWorld()
{
Template template;
var path = @"C:\templates\template.st";
var file = new FileInfo(path);
using (StreamReader reader = file.OpenText())
template = new Template(reader.ReadToEnd(), '$', '$'); // custom delimeter (defaults are "<" and ">")
template.Add("string", "Hello World!");
template.Add("array", new string[] { "Record A", "Record B", "Record C" });
template.Add("object", new { PropertyA = "A", PropertyB = "B" });
return template.Render();
}
}
}
Template File$! file: C:\templates\template.st !$
String:
$string$
Array:
$array:{it|$it$ ($i$)};separator=", "$
Object:
Property A = $object.PropertyA$
Property B = $object.PropertyB$
Gotchas
Upgrading from 3.2 to 4 today has been an unpleasant experience.
- Curly braces need to be escaped with a backslash within loops, I don't remember having to do this before.
$items:{item| \t{ ... item.property ... \} }$ - Speaking of loops, the "it" alias no longer works. You have to alias them every time now.
Good:
$items:{it| $it.property$ }$Bad:
$items:{ $it.property$ }$ - This was likely invalid before but you can't put your $ variables in if statements anymore.
Good:$if(mybool)$ ... $endif$
Bad:$if($mybool$)$ ... $endif$
0 comments:
Post a Comment