Awesome Open Source
Awesome Open Source


CI Nuget performance

Quality Gate Status Reliability Rating Security Rating

Bugs Code Smells Coverage

Stack Exchange questions GitHub issues questions GitHub issues help wanted

Blistering-fast Handlebars.js templates in your .NET application.

Handlebars.js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.

Check out the handlebars.js documentation for how to write Handlebars templates.

Handlebars.Net doesn't use a scripting engine to run a Javascript library - it compiles Handlebars templates directly to IL bytecode. It also mimics the JS library's API as closely as possible.


dotnet add package Handlebars.Net


string source =
@"<div class=""entry"">
  <div class=""body"">

var template = Handlebars.Compile(source);

var data = new {
    title = "My new post",
    body = "This is my first post!"

var result = template(data);

/* Would render:
<div class="entry">
  <h1>My New Post</h1>
  <div class="body">
    This is my first post!

Registering Partials

string source =
  {{> user}}

string partialSource =

Handlebars.RegisterTemplate("user", partialSource);

var template = Handlebars.Compile(source);

var data = new {
  names = new [] {
    new {
        name = "Karen"
    new {
        name = "Jon"

var result = template(data);

/* Would render:

Registering Helpers

Handlebars.RegisterHelper("link_to", (writer, context, parameters) => 
    writer.WriteSafeString($"<a href='{context["url"]}'>{context["text"]}</a>");

string source = @"Click here: {{link_to}}";

var template = Handlebars.Compile(source);

var data = new {
    url = "",
    text = "Handlebars.Net"

var result = template(data);

/* Would render:
Click here: <a href=''>Handlebars.Net</a>

This will expect your views to be in the /Views folder like so:

Views\layout.hbs                |<--shared as in \Views            
Views\partials\somepartial.hbs   <--shared as in  \Views\partials

Registering Block Helpers

Handlebars.RegisterHelper("StringEqualityBlockHelper", (output, options, context, arguments) => 
    if (arguments.Length != 2)
        throw new HandlebarsException("{{#StringEqualityBlockHelper}} helper must have exactly two arguments");

    var left = arguments.At<string>(0);
    var right = arguments[1] as string;
    if (left == right) options.Template(output, context);
    else options.Inverse(output, context);

var animals = new Dictionary<string, string>() 
	{"Fluffy", "cat" },
	{"Fido", "dog" },
	{"Chewy", "hamster" }

var template = "{{#each this}}The animal, {{@key}}, {{#StringEqualityBlockHelper @value 'dog'}}is a dog{{else}}is not a dog{{/StringEqualityBlockHelper}}.\r\n{{/each}}";
var compiledTemplate = Handlebars.Compile(template);
string templateOutput = compiledTemplate(animals);

/* Would render
The animal, Fluffy, is not a dog.
The animal, Fido, is a dog.
The animal, Chewy, is not a dog.

Register custom value formatter

In case you need to apply custom value formatting (e.g. DateTime) you can use IFormatter and IFormatterProvider interfaces:

public sealed class CustomDateTimeFormatter : IFormatter, IFormatterProvider
    private readonly string _format;

    public CustomDateTimeFormatter(string format) => _format = format;

    public void Format<T>(T value, in EncodedTextWriter writer)
        if(!(value is DateTime dateTime)) 
            throw new ArgumentException("supposed to be DateTime");

    public bool TryCreateFormatter(Type type, out IFormatter formatter)
        if (type != typeof(DateTime))
            formatter = null;
            return false;

        formatter = this;
        return true;

public void DateTimeFormatter(IHandlebars handlebars)
    var source = "{{now}}";

    var format = "d";
    var formatter = new CustomDateTimeFormatter(format);

    var template = handlebars.Compile(source);
    var data = new
        now = DateTime.Now
    var result = template(data);
    Assert.Equal(, result);


  • Formatters are resolved in reverse order according to registration. If multiple providers can provide formatter for a type the last registered would be used.

Compatibility feature toggles

Compatibility feature toggles defines a set of settings responsible for controlling compilation/rendering behavior. Each of those settings would enable certain feature that would break compatibility with canonical Handlebars. By default all toggles are set to false.

  • Areas
    • Compile-time: takes affect at the time of template compilation
    • Runtime: takes affect at the time of template rendering


If true enables support for Handlebars.Net helper naming rules. This enables helper names to be not-valid Handlebars identifiers (e.g. {{ one.two }}). Such naming is not supported in Handlebarsjs and would break compatibility.

  • Compile-time
public void HelperWithDotSeparatedName()
    var source = "{{ one.two }}";
    var handlebars = Handlebars.Create();
    handlebars.Configuration.Compatibility.RelaxedHelperNaming = true;
    handlebars.RegisterHelper("one.two", (context, arguments) => 42);

    var template = handlebars.Compile(source);
    var actual = template(null);
    Assert.Equal("42", actual);



Compared to rendering, compiling is a fairly intensive process. While both are still measured in millseconds, compilation accounts for the most of that time by far. So, it is generally ideal to compile once and cache the resulting function to be re-used for the life of your process.


Nearly all time spent in rendering is in the routine that resolves values against the model. Different types of objects have different performance characteristics when used as models.

Model Types

  • The absolute fastest model is a IDictionary<string, object> (microseconds).
  • The next fastest is a POCO (typically a few milliseconds for an average-sized template and model), which uses traditional reflection and is fairly fast.
  • Rendering starts to get slower (into the tens of milliseconds or more) on dynamic objects.
  • The slowest (up to hundreds of milliseconds or worse) tend to be objects with custom type implementations (such as ICustomTypeDescriptor) that are not optimized for heavy reflection.

A frequent performance issue that comes up is JSON.NET's JObject, which for reasons we haven't fully researched, has very slow reflection characteristics when used as a model in Handlebars.Net. A simple fix is to just use JSON.NET's built-in ability to deserialize a JSON string to an ExpandoObject instead of a JObject. This will yield nearly an order of magnitude improvement in render times on average.

Future roadmap



Pull requests are welcome! The guidelines are pretty straightforward:

  • Only add capabilities that are already in the Mustache / Handlebars specs
  • Avoid dependencies outside of the .NET BCL
  • Maintain cross-platform compatibility (.NET/Mono; Windows/OSX/Linux/etc)
  • Follow the established code format

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
c-sharp (12,431
dotnet (895
template-engine (133
handlebars (79
mustache (69