2

我们如何在 Handlebars.Net 中注册这两个 JavaScript 助手?

对于 Moment.js:

Handlebars.registerHelper("formatDate", function (datetime, format) {
    return moment(datetime).format(format);
});

对于 java 脚本计算:

Handlebars.registerHelper("formatPercent", function (val1, limit) {
    return Math.ceil(100 * val1 / limit);
});m
4

2 回答 2

4

自述文件给出了如何编写帮助程序的示例:

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>
*/

最重要的区别是在 .NET 中,帮助程序不返回值。相反,您将获得对TextWriter生成模板输出的引用。因此,您的助手可以通过该编写器将任何它想要的内容直接写入模板。包含一个.WriteSafeString()帮助程序来绕过默认编码。确保你的字符串实际上是安全的,当你这样做时不编码。

于 2016-06-23T14:04:29.647 回答
1

找到了。这个例子揭示了一些亮点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))
于 2016-06-14T04:01:27.877 回答