A lightweight, powerful, templating engine for C# and other .net-based languages.
Mustachio allows you to create simple text-based templates that are fast and safe to render. It's the heart of Postmark Templates, and we're ecstatic to provide it as Open Source to the .net community.
// Parse the template:
var sourceTemplate = "Dear {{name}}, this is definitely a personalized note to you. Very truly yours, {{sender}}"
var template = Mustachio.Parser.Parse(sourceTemplate);
// Create the values for the template model:
dynamic model = new ExpandoObject();
model.name = "John";
model.sender = "Sally";
// Combine the model with the template to get content:
var content = template(model);
// You can add support for Partials via Token Expanders.
// Token Expanders can be used to extend Mustachio for many other use cases, such as: Date/Time formatters, Localization, etc., allowing also custom Token Render functions.
var sourceTemplate = "Welcome to our website! {{{ @content }}} Yours Truly, John Smith.";
var stringData = "This is a partial. You can also add variables here {{ testVar }} or use other expanders. Watch out for infinite loops!";
var tokenExpander = new TokenExpander
{
RegEx = new Regex("{{{ @content }}}"), // you can also use Mustache syntax: {{> content }}
ExpandTokens = (s, baseOptions) => Tokenizer.Tokenize(stringData, baseOptions) // Instead of baseOptions, you can pass a new ParsingOptions object, which has no TokenExpanders to avoid infinite loops.
};
var parsingOptions = new ParsingOptions { TokenExpanders = new[] { tokenExpander } };
var template = Mustachio.Parser.Parse(sourceTemplate, parsingOptions);
// Create the values for the template model:
dynamic model = new ExpandoObject();
model.testVar = "Test";
// Combine the model with the template to get content:
var content = template(model);
Mustachio can be installed via NuGet:
Install-Package Mustachio
Mustachio contains a few modifications to the core Mustache language that are important.
each
blocks are recommended for handling arrays of values. (We have a good reason!){{ this.is.a.valid.path }}
and {{ ../this.goes.up.one.level }}
One awesome feature of Mustachio is that with a minor alteration in the mustache syntax, we can infer what model will be required to completely fill out a template. By using the each
keyword when interating over an array, our parser can infer whether an array or object (or scalar) should be expected when the template is used. Normal mustache syntax would prevent us from determining this.
We think the model inference feature is compelling, because it allows for error detection, and faster debugging iterations when developing templates, which justifies this minor change to 'vanilla' mustache syntax.