Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Handlebars.js with Backbone.Marionette

Is it possible to use the Handlebars.js with the Backbone.Marionette extension without reimplementing the Views render function? It seems that Marionette is relying on the convention that you use Backbone.js with underscores templating engine. But I really like the handlebar approach so I'm asking if I can the high-level-tools of Marionette with handlebars.

like image 353
Johannes Klauß Avatar asked Mar 29 '13 13:03

Johannes Klauß


4 Answers

A simple way to use Handlebars with Marionette is simply to define template in each View as a pre-compiled Handlebars template function. For instance:

var MyView = Backbone.Marionette.ItemView.extend({
    template: Handlebars.compile("Hello, {{name}}"),
    model: new Backbone.Model({name: "Steve"})
});

Marionette's default Renderer will detect that the template attribute is a function, and will call it accordingly.

See also the official documentation about this case : https://github.com/marionettejs/backbone.marionette/wiki/Using-handlebars-templates-with-marionette

and an other Q/A with requirejs + Marionette + Handlebars precompiled : Using precompiled handlebars templates with Marionette

like image 174
brettjonesdev Avatar answered Nov 13 '22 19:11

brettjonesdev


@brettjonesdev is correct, but one other addition here that I found worked well was:

var MyView = Backbone.Marionette.ItemView.extend({
  template: Handlebars.compile($("#assign-products-main-view").html()),
  model: new Backbone.Model({name: "Steve"})
});

This helps when searching the DOM.

like image 6
andrewmart.in Avatar answered Nov 13 '22 19:11

andrewmart.in


We can also make use of precompiled templates here.

var MyView = Backbone.Marionette.ItemView.extend({
template: Handlebars.templates['filename'],
model: new Backbone.Model({name: "Steve"})
});

This way we can remove the compilation role from Marionette.

like image 3
devil_io Avatar answered Nov 13 '22 20:11

devil_io


The current two answers do not exploit caching. Use this gist instead.

like image 2
Reza Salarmehr Avatar answered Nov 13 '22 21:11

Reza Salarmehr