通过JSON按需提供预编译的Handlebars模板

时间:2013-05-02 10:42:29

标签: javascript ember.js handlebars.js

我希望通过Handlebars - 请求将Ember.js模板发送到我的Ajax应用程序。我能够在服务器上编译它,我也能够提供类似以下输出(function)的内容String

Ember.TEMPLATES["authentication"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Ember.Handlebars.helpers; data = data || {};
  var buffer = '', stack1, hashTypes, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression;


  data.buffer.push("<h1>Hooray! It works!</h1>\r\n");
  hashTypes = {};
  options = {hash:{},contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data};
  data.buffer.push(escapeExpression(((stack1 = helpers.outlet),stack1 ? stack1.call(depth0, "main", options) : helperMissing.call(depth0, "outlet", "main", options))));
  return buffer;

});

这正是我能够从收到的String对象中获得的JSON。现在,我想将此预编译模板添加到Ember.TEMPLATES对象中,如下所示:

if(typeof data.template === 'string' && data.template != '') {
                  var escapedTemplateString =
                      data.template.replace(/\\n/g, "\\n").replace(/\\r/g, "\\r").replace(/\\t/g, "\\t");

                  Ember.TEMPLATES[templateName] = Ember.Handlebars.template(new Function(escapedTemplateString));
                }

但是这将整个'stringified'函数包装到另一个anonymous function(){}中,我没有模板。如果我使用eval解压缩'stringified'函数,则模板为undefined ...

有没有人知道如何在没有任何“字符串化”函数包装的情况下获得function? 非常感谢您提前的时间;)

1 个答案:

答案 0 :(得分:0)

没关系......我忘了将Ajax请求声明为async: false,以便渲染过程等待加载模板。

另外,我将函数调用从eval( escapedTemplateString )更改为eval( "(" + escapedTemplateString + ")" )

- &GT;现在一切都很好了