Basic Template Execution

This is the simplest most concise template execution.

var parser = new FluidParser();
var template = parser.Parse("My name is Deane.");
var result = template.Render();

We did three things:

  1. Got a parser
  2. Parsed a “template” (well, a string anyway…)
  3. Executed the template

Some notes:

  • FluidParser is thread-safe. Create it once as a singleton and hang onto it.
  • Any parsed template is also thread-safe and can be re-used. If the underlying template hasn’t changed, don’t re-parse it.

This means that if your templates don’t change and you’ve cached them, you’ll usually just do #3 above – render a pre-parsed template.

Now, clearly the above example is pointless since there’s no output or logic in the template. We just outputted the input.

To perform a simple token replacement, we need to establish a TemplateContext, which is a container for all the dynamic data that goes into a template, then place an identifier in the template to replace with that data.

var parser = new FluidParser();
var template = parser.Parse("My name is {{ name }}.");

var context = new TemplateContext(new { name = "Deane"});

var result = template.Render(context);
My name is Deane.

Accessing object properties works the same way as primitives.

var person = new { Name = "Deane" };
context.SetValue("person", person);
My name is {{ person.Name }}

Note that this will not work unless you have granted access to the members of a class, or set the unsafe option (see Member Access).

Also note that you cannot call methods on objects. You can only retrieve properties. (There are some ways to circumvent this using custom filters, but it takes some code. We’ll talk more about this later.)

If you are not any getting output, see Troubleshooting: No Output.