【问题标题】:Handlebars precompiled templates returns undefined valueHandlebars 预编译模板返回未定义值
【发布时间】:2014-05-01 11:58:05
【问题描述】:

我有一个模板文件 test_temp.handlebars。它的内容是,

<div>Hello {{name}}</div>

我在命令行中使用命令编译了模板,

handlebars test_temp.handlebars -f test_temp.js

test_temp.js 文件的内容是,

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

现在我在我的 html 中阅读我的预编译模板。

var compiledTemplate = Handlebars.templates['test_temp'];
var temp_html = compiledTemplate({ name: 'World' });
console.log(temp_html);  //undefined

这里返回给 temp_html 的值是未定义的。 请让我知道如何将此 temp_html 放入 div 中。

$("#tempdiv").html(temp_html);

当我更新 div 内的 temp_html 时,抛出的错误是,

"Uncaught TypeError: undefined is not a function"

如何获取预编译的模板值并将其插入到 div 中。

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:

    看到这个答案: https://stackoverflow.com/a/22214119/432089

    如果您从 npm 下载车把,您将获得 2.0 alpha 版本,而不是稳定的 1.3.0 版本。换句话说,很可能您有 2.0 alpha 预编译模板,但您使用的是 1.3.0 运行时 JS。

    【讨论】:

    • 非常感谢您的链接,我得到了答案,它工作正常。
    【解决方案2】:

    检查这个小提琴:

    http://jsfiddle.net/8TMw4/

    <script id="some-template" type="text/x-handlebars-template">
        <div>Hello {{name}}</div>    
    </script>
    
    var source = $("#some-template").html(); 
    var template = Handlebars.compile(source); 
    console.log(template); 
    

    【讨论】:

    • 您的代码在浏览器中编译模板。这将起作用。我需要在后端服务器中编译我的模板并像我的代码一样读取 js 文件,但它不起作用。
    【解决方案3】:

    我已经使用以下过滤器完成了这项任务:

    • 在后端预编译模板(使用您喜欢的构建工具)。
    • 将预编译的模板加载到 Ember.TEMPLATES['"+templateName+"']。
    • 您必须遵循 ember 命名约定,以便 Ember 识别您的路径、视图或组件模板所在的位置。这是Ember.DefaultResolverComponentLookup 的工作。如果您实现自定义解析器并将其分配给应用程序实例,则可以定义特定的命名约定。

    您可以查看demo example,其构建工具是 rake-pipeline 或 broccoli。

    【讨论】:

    • 感谢您的回复。我已经使用 ember-precompile 预编译了我的 .hbs 文件。现在我如何阅读模板并将其放置在 div 中。我读到, var compiledTemplate = Em.TEMPLATES['precompile'];compiledTemplate({ name: 'World' });但无法读取未定义错误的属性“推送”
    猜你喜欢
    • 2014-08-29
    • 2013-08-19
    • 2012-04-10
    • 2013-03-14
    • 1970-01-01
    • 2022-01-03
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多