How would we register these two JavaScript helpers in Handlebars.Net?
For Moment.js:
Handlebars.registerHelper("formatDate", function (datetime, format) {
return moment(datetime).format(format);
});
For a java script calculation:
Handlebars.registerHelper("formatPercent", function (val1, limit) {
return Math.ceil(100 * val1 / limit);
});m
The readme gives an example for how to write 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 = "https://github.com/rexm/handlebars.net",
text = "Handlebars.Net"
};
var result = template(data);
/* Would render:
Click here: <a href='https://github.com/rexm/handlebars.net'>Handlebars.Net</a>
*/
The most important difference is in .NET, the helper doesn't return a value. Rather, you're given a reference to the TextWriter
that is generating the template output. So your helper can write whatever it wants directly to the template via that writer. There is a .WriteSafeString()
helper included to bypass the default encoding. Make sure your string is actually safe to not encode when you do that.
Found it. This example sheds some light https://gist.github.com/rexm/e1a045b9f76a48de642e
Handlebars.RegisterHelper("formatDate", New HandlebarsHelper(Sub(w, c, p)
w.WriteSafeString("moment(" + p(0) + ").format(" + p(1) + ");")
End Sub))
Handlebars.RegisterHelper("formatPercent", New HandlebarsHelper(Sub(w, c, p)
If p(1) = 0 Then
w.WriteSafeString("0")
Else
w.WriteSafeString("Math.ceil(" + 100 * p(0) / p(1) + ");")
End If
End Sub))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.