Handlebars.Net How to change behavior if data does not exist

1k views Asked by At

In Handlebars.Net, if there is no matching field, it just places a blank there.

string source = @"My name is {{Name}} and I work at {{Job}}";
var template = Handlebars.Compile(source);
var data = new {
    Job = "Walmart"
};
var result = template(data);

Results in this because the {{Name}} is not in the data.

My name is and I work at Walmart

Is there a setting to say, just don't replace it if the data field does not exist?

I'd like for it to return:

My name is {{Name}} and I work at Walmart

3

There are 3 answers

0
Oleh Formaniuk On BEST ANSWER

There are two options:

  1. Supported in 1.x: use UnresolvedBindingFormatter

    handlebars.Configuration.UnresolvedBindingFormatter = "('{0}' is undefined)";

  2. Supported starting from 2.0.0-preview-1: use helperMissing hook

    handlebars.RegisterHelper("helperMissing", (context, arguments) =>
    {
        var name = arguments.Last().ToString();
        return "{{" + name.Trim('[', ']') + "}}";
    });
    

For more details see this GitHub issue.

0
76484 On

I think you would have to use an #if, as in:

My name is {{#if Name}}{{Name}}{{else}}\{{Name}}{{/if}} and I work at {{Job}}

Note: I owe thanks to this answer for how to tell Handlebars to render the braces.

0
lisa On

For version Handlebars.Net Version="2.1.4".

var handlersTemplate = "My Name: {{Name}} Work {{Work}}";
var data = new { Work = "Remote" };
var result = CompileHandlebars(handlebarsTemplate,data);

private static string CompileHandlebars(string handlebarsTemplate, dynamic data)
{
    var handlebars = Handlebars.Create();
    var format = "{0}";
    handlebars.RegisterHelper("helperMissing",
        (in HelperOptions options, in Context context, in Arguments arguments) =>
        {
            return "{{" + string.Format(format, options.Name.TrimmedPath) + "}}";
        });

    var template = handlebars.Compile(handlebarsTemplate);
    return template(data);
}

Then end result would be: result = "My Name: {{Name}} Work Remote";