使用指定值编译Ember模板

时间:2013-10-23 19:57:27

标签: javascript ember.js handlebars.js

我需要从Ember.TEMPLATES获取模板,使用指定对象编译它并获取其原始HTML值。

Ember.TEMPLATES内容(使用gruntjs生成)返回一个函数,似乎已经通过Handlebars.template()函数传递,所以例如我会这样:

Ember.TEMPLATES["test"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
  var buffer = '', hashTypes, hashContexts, escapeExpression=this.escapeExpression;


  data.buffer.push("<strong>hello world ");
  hashTypes = {};
  hashContexts = {};
  data.buffer.push(escapeExpression(helpers._triageMustache.call(depth0, "test", {hash:{},contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data})));
  data.buffer.push("</strong>\n");
  return buffer;

});

并希望使用JSON对象中的新值编译该模板。

我根据我在Ember代码中看到的内容尝试了类似的东西:

var test = Ember.TEMPLATES['test'];
var compiled = test({ test: 'value' });

我认为它可能有用,但实际上并没有。

基本上我想用标准把手做:

Handlebars.compile('<strong>{{hello}}</strong>', { hello: 'world' });

有没有办法编译具有指定值的模板,并使用Emberjs获取HTML结果?

1 个答案:

答案 0 :(得分:3)

Ember do some modifications in handlebars compiler以启用计算属性的使用,在模型更改时使模板更新等。

如果您看到view render method,它会超过template(context),它会使用上下文和一些私人自定义数据。所以Handlebars.compileEmber.Handlebars.compile不同,我认为来自Ember.Handlebars.compile的编译模板不能在Ember.View之外使用。

使用text/x-raw-handlebars而不是text/x-handlebars标记脚本类型,使模板使用Handlebars.compile进行编译。

以下示例可以使用,但没有ember功能:

<强>模板

<script type="text/x-raw-handlebars" data-template-name="custom-template">
    First name: {{firstName}} <br/>Last name: {{lastName}}
</script>

<强>的Javascript

App = Ember.Application.create({
    ready: function() {
        var template = Ember.TEMPLATES['custom-template'];                    
        var html = template({ firstName: 'Tom', lastName: 'Dale' });
        $('body').append(html);
    }
});

您可以在此处查看此示例http://jsfiddle.net/marciojunior/MC8QB/