ember hbs templates as separate files

前端 未结 3 1994
春和景丽
春和景丽 2020-12-28 17:54

I want to run ember.js (version 1.0.0 Final) examples provided on their first page.

They divided each handlebar template in separate file with .hbs exte

3条回答
  •  醉梦人生
    2020-12-28 18:39

    When you have templates in different files, you have to load them and compile them as EmberJS doesn't detect files. There are few ways to do that.

    1) Load them to Ember.TEMPLATES: Ember loads the templates and pushes them in to an object Ember.TEMPLATES. it stores the templates content with small name key as per EmberJS Naming conventions. So we ourselves can push the templates after compiling them.

    Eg: If you have a template with the name 'post', load the post.hbs file through AJAX request then set,

    // "data" is html content returned from Ajax request
    Ember.TEMPLATES['post'] = Ember.Handlebars.compile(data) 
    

    So now you can access the template directly as

       {{partial 'post'}} 
    

    in handlebars or set as templateName for any view classes.

    App.OtherView = Ember.View.extend({
       templateName: 'post'
    });
    

    So, you may have to end up loading all HBS files through AJAX request and compile them before loading your application. This is a big overhead for an application.

    In order to ease this, we can pre-compile all templates and save them as JS(which actually pushes them in to the Ember.TEMPLATES object) and just load that JS. This can be achieved using a plug-in ember-templates which is also available as a grunt job grunt-ember-templates.

    2) The second way is create a view object and set the compiled code to the template of each view after the AJAX request. The text plug-in of requirejs helps you to do that.

    As nowadays Ember people suggest not to create a view object unless required, I suggest you follow the first way. The precompiled one is the best option which reduces a lot of work every time you create a template.

    UPDATE : There are some project building tools which takes care of compiling handlebars templates. Yeoman and Ember-Cli are the ones you can have a look once.

提交回复
热议问题