0
votes

I'm totally new to Ember and I'm actually trying to organize my code a bit. To do so, I try to load my Handlebars templates from external files. Everything works fine until the moment I want to compile them.

var url = 'js/app/templates/index.hbs', templateName = url.replace('.hbs', ''), 
    datas = {name:'John'};

var load_tpl_success = function(hbs_tpl) {
    Em.TEMPLATES[templateName] = Em.Handlebars.compile(hbs_tpl)(datas);
    Em.$('body').append(Em.TEMPLATES[templateName]);
};

Em.$.ajax({ url: url, async: false, success: load_tpl_success});

This crashes and gives me te error : Uncaught TypeError: Cannot call method 'push' of undefined

BUT, if I use :

Handlebars.compile(hbs_tpl)(datas)

Everything works well until I start using {{input}} and others made by Ember. So basically it looks like Handlebars is working but not Ember... I need Ember ahah

I'm using the last version of Ember coming with its own Handlebars (old version).

Does anyone have an idea?

1

1 Answers

1
votes

Em.Handlebars.compile returns a template function that can be used for rendering. You are creating the template, then immediately calling the function to compile the template.

Em.TEMPLATES[templateName] = Em.Handlebars.compile(hbs_tpl)(datas);

That line is not creating a template, it's creating one then rendering it. So while Ember.js is expect a template, you're giving it a rendered template (a string). You should never be directly calling the template method, that is done for you by Ember.js. So this line is a big no-no.

Em.$('body').append(Em.TEMPLATES[templateName]);

The only thing you should be doing with templates is creating them and telling Ember.js where they are. You can either do that by including them in the HTML via script tags, or by putting them in the Em.TEMPLATES hash. But if you're doing the latter, make sure you don't attempt to go to the route using that template before you put it there.

TL;DR: You're too new too Ember.js to be worrying about pre-compiling or lazy-loading templates. Put them in script tags like in the guide until you're more familiar with their workings.

EDIT: Also, this applies in general, but especially when working with Ember.js: never run a synchronous AJAX request. There are very few times you'd want to do that, and this is not one of them.