David Walker
David Walker / Grax32

David Walker / Grax32

PhilTemplate is a simple and flexible template solution

PhilTemplate is a simple and flexible template solution

David Walker's photo
David Walker
·Jun 9, 2022·

2 min read

PhilTemplate is a template fill solution for templates that do not contain logic. It accepts a resolution function, allowing you to resolve against any data source you choose to specify, i.e. configuration, dictionary, switch statement, custom function. It is simple to use directly or as a base class for template functionality.

Both instant templates and compiled templates are supported.

For singular or infrequent template, the ApplyStringTemplate function accepts the template and the key resolution function, defaulting to using the "{{" and "}}" strings to indicate the values needing replacement.

var myValues = new Dictionary<string, string>{{"name", "Horatio"}};
const string myTemplate = "My name is {{name}}.  I like my templates to start with {{}} and end with }}";
var myTemplateResult = TemplateOnDemand.ApplyStringTemplate(myTemplate, key => myValues[key]);
Console.WriteLine(myTemplateResult);

The resulting output will be:

My name is Horatio.  I like my templates to start with {{ and end with }}

Any delimiter can be specified. For example,

var myValues = new Dictionary<string, string>();
myValues["name"] = "Marco";
myValues["title"] = "Race Car Driver";
const string myTemplate = "I am {name}, I am a {title} and I also like templates, but mine start with {} and end with }";

var myTemplateResult = TemplateOnDemand.ApplyStringTemplate(myTemplate, key => myValues[key], "{", "}");
        Console.WriteLine(myTemplateResult);

With the corresponding output of:

I am Marco, I am a Race Car Driver and I also like templates, but mine start with { and end with }

For more information, see the following:

 
Share this