用 http://handlebarsjs.com 上的例子
var source=document.getElementById('entry-template').innerHTML;
var template = Handlebars.compile(source);
提示
TypeError: Handlebars.compile is not a function
然后用 Firebug 看了一个 没有 complie
方法, 有个 template
然后用 template
调用
var template = Handlebars.template(source);
返回是一个函数
template(data)
这样调用提示 templateSpec.call is not a function
3 回复
看下Handlebars.template的定义:
function template(templateSpec, env) {
if (!env) {
throw new Exception("No environment passed to template");
}
// Note: Using env.VM references rather than local var references throughout this section to allow
// for external users to override these as psuedo-supported APIs.
var invokePartialWrapper = function(partial, name, context, helpers, partials, data) {
var result = env.VM.invokePartial.apply(this, arguments);
if (result != null) { return result; }
if (env.compile) {
var options = { helpers: helpers, partials: partials, data: data };
partials[name] = env.compile(partial, { data: data !== undefined }, env);
return partials[name](context, options);
} else {
throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
}
};
// Just add water
var container = {
escapeExpression: Utils.escapeExpression,
invokePartial: invokePartialWrapper,
programs: [],
program: function(i, fn, data) {
var programWrapper = this.programs[i];
if(data) {
programWrapper = program(i, fn, data);
} else if (!programWrapper) {
programWrapper = this.programs[i] = program(i, fn);
}
return programWrapper;
},
merge: function(param, common) {
var ret = param || common;
if (param && common && (param !== common)) {
ret = {};
Utils.extend(ret, common);
Utils.extend(ret, param);
}
return ret;
},
programWithDepth: env.VM.programWithDepth,
noop: env.VM.noop,
compilerInfo: null
};
return function(context, options) {
options = options || {};
var namespace = options.partial ? options : env,
helpers,
partials;
if (!options.partial) {
helpers = options.helpers;
partials = options.partials;
}
var result = templateSpec.call(
container,
namespace, context,
helpers,
partials,
options.data);
if (!options.partial) {
env.VM.checkRevision(container.compilerInfo);
}
return result;
};
}
传入的参数是一个function,这也是为什么你调用Handlebars.template(source)之后会报 templateSpec.call is not a function 的错误。
按官网的例子写的
<script type="text/x-handlebars-template" id='xx'>
<h1>{{title}}</h1>
<ul>
{{#names}}
<li>{{name}}</li>
{{/names}}
</ul>
</script>
<script type="text/javascript">
var source=document.getElementById('xx').innerHTML;
var template = Handlebars.compile(source);
console.log(template);
var data = {"title": "Story", "names": [{"name": "Tarzan"}, {"name": "Jane"}]};
console.log(template(data));
</script>