繁体   English   中英

如何通过Handlebars.precompile(vs CLI)使用模板

[英]How to use templates via Handlebars.precompile (vs CLI)

我在.NET环境中,我们不能使用Node.js(要求,愚蠢的事情)。 我们有一个自定义的Backbone应用程序,并使用Handlebars作为客户端模板。 由于此项目的限制,我们手动使用Handlebars.precompile预编译所有模板。 我已经做了一些google-fu并通过Stackoverflow搜索但是在Handlebars.precompile上没有看到太多有用的文档(这个输出与使用CLI工具不同)。 我的问题是:一旦我以编程方式预编译Handlebars模板,它们如何被使用? 此实现不会将它们添加到Handlebars.templates命名空间。

例如,我们将采用一个基本模板(称为Stuff.handlebars):

{{!-- begin template --}}
    <strong> {{test}} </strong>
{{!-- end template --}}

这是使用Handlebars.precompile的输出:

function (Handlebars, depth0, helpers, partials, data) {
    this.compilerInfo = [4, '>= 1.0.0'];
    helpers = this.merge(helpers, Handlebars.helpers);
    data = data || {};
    var buffer = "",
        stack1, helper, functionType = "function",
        escapeExpression = this.escapeExpression;


    buffer += "<strong> ";
    if (helper = helpers.test) {
        stack1 = helper.call(depth0, {
            hash: {},
            data: data
        });
    } else {
        helper = (depth0 && depth0.test);
        stack1 = typeof helper === functionType ? helper.call(depth0, {
            hash: {},
            data: data
        }) : helper;
    }
    buffer += escapeExpression(stack1) + " </strong>";
    return buffer;
}

当通过node.js把手编译器( handlebars stuff.handlebars -f test.js )运行时,输出如下:

(function () {
    var template = Handlebars.template,
        templates = Handlebars.templates = Handlebars.templates || {};
    templates['stuff'] = template({
        "compiler": [5, ">= 2.0.0"],
        "main": function (depth0, helpers, partials, data) {
            var helper, functionType = "function",
                escapeExpression = this.escapeExpression;
            return "\r\n    <strong> " + escapeExpression(((helper = helpers.test || (depth0 && depth0.test)), (typeof helper === functionType ? helper.call(depth0, {
                "name": "test",
                "hash": {},
                "data": data
            }) : helper))) + " </strong>\r\n";
        },
        "useData": true
    });
})();

我的问题是这样的:我如何适当地使用以编程方式创建的Handlebars模板并将数据传递给它们? 我目前正在将它们命名为App.Templates.mytemplatename = ...output of handlebars.precompile(source)...

所以,例如设置模板我是:

var foo = $("#foo");
$(foo).html(Handlebars.template(App.Templates.Stuff));

这输出正确减去数据。 如何将数据传递给此?

请记住,我只是在我试图传递数据的页面上使用handlebars.runtime.js库(否则我将不会完成所有这些步骤)。

编辑:好的,我找到了答案。

使用上面的例子,我创建了一个名为“testObj”的对象:

testObj = { test: "foo bar" };

接下来,我将Handlebars.template()调用分配给变量:

var template = Handlebars.template(App.Template.Stuff);

最后,我将对象作为参数传递:

template(testObj);

其输出是: "foo bar"

使用上面的例子,我创建了一个名为“testObj”的对象:

testObj = { test: "foo bar" };

接下来,我将Handlebars.template()调用分配给变量:

var template = Handlebars.template(App.Template.Stuff);

最后,我将对象作为参数传递:

template(testObj);

其输出是: "foo bar"

暂无
暂无

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

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