Marionette LayoutView removed my root HTML element

2019-08-14 14:17发布

This is my template file outerLayout.html:

<section id="index-wrapper">
    <navigation id="menu">menu1</navigation>
    <article id="content">main content</article>
    <footer id="footer">footer</footer>
</section>

This is my outerLayout.js

var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var Maronette = require('backbone.marionette');
var compiledTpl = require('./outerLayout.html');
// console.info('compiledTpl({})', compiledTpl({}));
    console.info('compiledTpl({})', compiledTpl({}));
var OuterLayout = Backbone.Marionette.LayoutView.extend({
    template: compiledTpl({}), 
    el: '#main',
    regions: {
        menu: '#menu', 
        content: '#content', 
        footer: '#footer'
    }
});

module.exports = new OuterLayout();

Here are the code in router to render the layoutView:

var AppRouter = Backbone.Marionette.AppRouter.extend({
    routes : {
        '': 'index'
    }, 
    index : function () {
        var outerLayout = require('../layout/outerLayout/outerLayout');
        outerLayout.render();

    }
    }    
});

The render result is:

enter image description here

But the result should be this one:

enter image description here

In short words, the render function removed tag which is not my objective. How can I fix it?

1条回答
混吃等死
2楼-- · 2019-08-14 14:37

Problems comes from Marionette.TemplateCache.loadTemplate and Marionette.TemplateCache.compileTemplate.

As you can see from annotations of functions you need to override them in order to user other templates rather than Underscore's _.template().

And the actual line from definition of loadTemplate which is responsible for this behavior (your issue) is:

var template = Backbone.$(templateId).html();

cause, in case you didn't rewrited loadTemplate and compileTemplate, Marionette will assume that you using default underscore's templates (If you will try it with underscore it will work as expected).

Example:

If you using Handlebars for templates:

Marionette.TemplateCache.prototype.compileTemplate = function (yourTemplate) {
    if ($.isFunction(yourTemplate)) {
        return yourTemplate;
    } else {
        return Handlebars.compile(yourTemplate);
    }
};

Marionette.TemplateCache.prototype.loadTemplate = function (yourTemplateId) {

    var yourTemplate;

    if (Handlebars.templates && Handlebars.templates[yourTemplateId]) {
        // from cache
        yourTemplate = Handlebars.templates[yourTemplateId];
    } else {
        // load it here
    }
    return yourTemplate;
};

So just rewrite these methods and you ready to go!

查看更多
登录 后发表回答