3
votes

I need to get a template from Ember.TEMPLATES, compile it with a specified object and get its raw HTML value.

Ember.TEMPLATES content (generated using gruntjs) returns a function and seems to be already passed through Handlebars.template() function so for example I would have this:

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;

});

and would like to compile that template with new values from a JSON object.

I tried something like that based on what I've seen in Ember code:

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

I thought it might work but it doesn't actually.

Basically I'd like to do like with standard handlebars :

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

Is there any way to compile a template with specified values, and get the HTML result using Emberjs?

1
What you have on Ember.TEMPLATES["test"] it's a pre-compiled template. Could you get the source and compile that one as you have in your last example?Miguel Madero

1 Answers

3
votes

Ember do some modifications in handlebars compiler to enable the use of computed properties, make templates update when model changes etc.

If you see the view render method, it does more than template(context), it use the context and some private custom data. So Handlebars.compile is diferent of Ember.Handlebars.compile and I think that compiled templates from Ember.Handlebars.compile, is not intended to be used outside of a Ember.View.

Marking script types with text/x-raw-handlebars, instead of text/x-handlebars make the template be compiled with Handlebars.compile.

The following sample will work, but without the ember features:

Template

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

You can see this sample here http://jsfiddle.net/marciojunior/MC8QB/