Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use EJS templates with backbone.marionette?

So far I have been using EJS templates in my Rails/Backbone.js application. I really want to start using backbone.marionette. What can I do to make it work with EJS?

MyView = Backbone.Marionette.ItemView.extend({
  template: "#some-template"
});

It says in the docs that I need to provide a jQuery selector to the template attribute but I don't think that my EJS templates have one.

Update:

This is how I would use templates to render my views normally:

TasksTree.Views.TaskItem = Backbone.View.extend({
...
  render: function() {
    ...
    this.$el.html(JST['tasks_tree/item'](options));
    return this;
  }

})

And I have templates folder with item.jst.ejs file that looks like that:

<li>
  <label><%= taskTitle %></label>
</li>

My templates folder is included in application.js

like image 268
lanan Avatar asked Dec 21 '22 23:12

lanan


2 Answers

There's a section in the docs that shows several examples of replacing the rendering mechanism, as well:

http://derickbailey.github.com/backbone.marionette/#backbone-marionette-renderer/custom-template-selection-and-rendering

Seeing that JST provides the templates for you, and you don't need to cache them in any other way, though, you could skip past most of the functionality built in to Marionette's Renderer object and replace the render function entirely.


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

You would also replace the use of teh template attribute on views with the template path instead of a jquery selector:


Backbone.Marionette.ItemView.extend({
  template: "tasks_tree/item"
});

Hope that helps. If not, let me know.

like image 84
Derick Bailey Avatar answered Dec 28 '22 06:12

Derick Bailey


I found this reference to be quite helpful: https://github.com/marionettejs/backbone.marionette/wiki/Using-jst-templates-with-marionette

You could replace the render function with something along these lines, which provides better error handling and flexibility.

Marionette.Renderer.render = function(template, data) {
    if(typeof template === 'function') {
        return template(data);
    }
    else {
        if(!JST[template]) throw "Template '" + template + "' not found!";
        return JST[template](data);
    }
};

You can then specify the template path (as previously mentioned):

Backbone.Marionette.ItemView.extend({
    template: "tasks_tree/item"
});

Or if your template is very simple, you can use a function to return just a string:

Backbone.Marionette.ItemView.extend({
    template: function(data) {
        return "<div>" + data.attribute + "</div>";
    }
});
like image 33
cockroachbill Avatar answered Dec 28 '22 07:12

cockroachbill