Getting started

edit

Install the package

Add the Meziantou.Framework.Templating package to a project:

dotnet package add Meziantou.Framework.Templating

The examples of this documentation omit the using directives: add using Meziantou.Framework.Templating;. They are tests: an Assert.Equal shows the text the template produces.

Render a template

Load the template, declare its arguments, and run it with their values:

using var template = new Template();
template.Load("Hello <%=Name%>!");
template.Arguments.Add(new TemplateArgument("Name", typeof(string)));
var result = template.Run("Meziantou");
Assert.Equal("Hello Meziantou!", result);
  • Load reads the template. <%= Name %> writes the value of the C# expression Name; the rest is text, written as is.
  • Arguments declares the values the template receives. Each argument becomes a C# parameter, with its name and its type.
  • Run compiles the template the first time it is called, runs it, and returns the text. The values are passed in the order of the arguments.
  • Template is disposable: disposing it unloads the compiled code. See Compilation and memory.

Loop and test conditions

The code of <% ... %> blocks runs as C# statements, so the text between them can be repeated or skipped:

using var template = new Template();
template.Load("Numbers: <% for(int i = 1; i <= 5; i++) { %><%= i %><% } %>");
var result = template.Run();
Assert.Equal("Numbers: 12345", result);

The other blocks, and how a template handles line breaks, are described in Template syntax.

Reuse a compiled template

Compiling a template takes much longer than running it. Keep the Template instance and run it as many times as you need; Build compiles it in advance, for instance when your application starts:

using var template = new Template();
template.Load("Hello <%=Name%>");
template.Arguments.Add(new TemplateArgument("Name", typeof(string)));

// Compile the template
template.Build(CancellationToken.None);

// Run multiple times (compiled code is reused)
var result1 = template.Run("Alice");
var result2 = template.Run("Bob");
Assert.Equal("Hello Alice", result1);
Assert.Equal("Hello Bob", result2);

Next steps