简体   繁体   English

如何在Handlebars.net注册JavaScript助手

[英]How to register JavaScript helpers with Handlebars.net

How would we register these two JavaScript helpers in Handlebars.Net? 我们如何在Handlebars.Net中注册这两个JavaScript帮助器?

For Moment.js: 对于Moment.js:

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

For a java script calculation: 对于Java脚本计算:

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. 最重要的区别在于.NET中,帮助程序不返回任何值。 Rather, you're given a reference to the TextWriter that is generating the template output. 相反,您将获得对生成模板输出的TextWriter的引用。 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. 有一个.WriteSafeString()帮助器可以绕过默认编码。 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 此示例提供了一些启示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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM