Skip to content

Using pre compiled templates

derickbailey edited this page Aug 14, 2012 · 3 revisions

If you're using v0.9.7 or later, you can specify a template function as the template setting for any view that supports templates.

function myTemplate(){ return "<div>some html</div>"; }

Backbone.Marionette.ItemView.extend({
  template: myTemplate
});

If you're using a v0.9.x version prior to that, or if you need more control over how the pre-compiled template is rendered, you can use the following code.

Using a pre-compiled template system, such as TPL or other plugins and add-ons requires one method to be overridden in the Renderer object to make this work:

Backbone.Marionette.Renderer.render = function(template, data){
  return template(data);
}

Then, you can specify your pre-compiled template as the template parameter for any view, and it will be rendered correctly:

var myTemplate = // some pre-compiled template function

MyView = Backbone.Marionette.ItemView.extend({
  template: myTemplate
});

This works equally as well for RequireJS plugins that load templates as functions, or for using your own compilation of templates or functions that simply return HTML strings.