Handlebars预编译模板返回未定义的值

时间:2014-04-26 03:18:33

标签: javascript ember.js handlebars.js

我有一个模板文件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中。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

检查这个小提琴:

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); 

答案 2 :(得分:0)

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

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

你可以看看这个demo example,它的构建工具是rake-pipeline或broccoli。