Search code examples
backbone.jsmustachemarionette

How to use Backbone.Marionette.ItemView with Mustache


The following code works fine using Backbone.Marionette.ItemView but not Mustache.

Backbone.Marionette.ItemView - no Mustache

I would like to use the same code but loading the template varaible using Mustache.

Here is my code:

Backbone.Marionette.ItemView - with Mustache

Any idea why my code does not work and why?

Thanks


Solution

  • Marionette assumes the use of UnderscoreJS templates by default. Simply replacing the template configuration for a view isn't enough. You also need to replace how the rendering process works.

    In your simple example, you only need to override the Marionette.Renderer.render function to call Mustache, and then set the template of your views to the string template that you want:

    
    Backbone.Marionette.Renderer.render = function(template, data){
      return Mustache.to_html(template, data);
    }
    
    var rowTemplate = '{{ username }}{{ fullname }}';
    
    // A Grid Row
    var GridRow = Backbone.Marionette.ItemView.extend({
        template: rowTemplate,
        tagName: "tr"
    });
    

    Note that your JSFiddle still won't work even when you put this code in place, because the GridView is still using a jQuery selector/string as the template attribute. You'll need to replace this with the same type of template function to return mustache.

    http://jsfiddle.net/derickbailey/d7qDz/