How to integrate Handlebars template to Marionette

2020-07-30 00:20发布

问题:

In my app, I am using the handlebars template plugin, I am little bit confused here, how can i integrate handlebars template to marionette Item View which is using separate template?

here is my code :

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'hbs!scripts/templates/login/loginTemp'], // this is my handlebars template.
    function ($,_,Backbone,Marionette,loginTemplate) {
        "use strict";
        socialApp = window.socialApp || {};

        socialApp.loginView = Backbone.Marionette.ItemView.extend({
            tagName:'div',
            className:'loginContainer',
            template: '#loginTemplate' //this is template for login alone (from DOM )
        });

        return socialApp.loginView;
    }
);

"loginTemp" - has all details what i require for login template.

回答1:

You could override Marionette.TemplateCache.prototype.compileTemplate function to achieve needed behavior:

 Marionette.TemplateCache.prototype.compileTemplate = function (yourRawTemplate) {
        // In case if template is function
        if (_.isFunction(yourRawTemplate)) {
            return yourRawTemplate;
        } else {
            return Handlebars.compile(yourRawTemplate);
        }
 };


回答2:

My "Marionette-Handlebars Boilerplate" might help you:
https://github.com/yuraji/marionette-handlebars-boilerplate



回答3:

If you are using regions in your marionette application, such as

socialApp.addRegions({
  loginRegion:'<id of the region>'
})

and if your template is written inside a script tag, then you can easily render your template in this manner:

//defining the view
socialApp.loginView = Marionette.ItemView.extend({
  template:Handlebars.compile(document.getElementById('loginTemplate').innerHTML),
  ...
  ...//other code and view logic
});

and then,

var loginView = new socialApp.loginView();  //creating instance of the view
socialApp.loginRegion.show(loginView);  //rendering it inside the region