Reputation: 2748
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
Upvotes: 0
Views: 1277
Reputation: 76
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";
Upvotes: 0
Reputation: 191
There are two options:
Supported in 1.x: use UnresolvedBindingFormatter
handlebars.Configuration.UnresolvedBindingFormatter = "('{0}' is undefined)";
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.
Upvotes: 5