Tag Archives: perl

Use Backbone (Underscore) templates with Mojolicious

Mojolicious uses it’s own embeded Perl parser and the embeded variables look something like this:

<%= $var %>

Underscore uses this as their embeded vars:

<%= var %>

So unless we use a different template engine, we cannot place these underscore templates inline with mojolicious templates because it will try to parse the Javascript template.

Here is how I get around it:

1. Create the template as a plain html file.
A.The file name of this template will be user.html:

<%= first_name %> <%= last_name %> 

2. Place the html file inside of your public directory in the mojo tree.

3. Create a javascript function that does grabs the template when you need it:

window.template = function(id){
    var theTemplate = ""

    $.ajax({
	url:"/templates/"+id+".html",
	success: function(data){
	  theTemplate = data;
    },
	async: false
	});

return _.template(theTemplate); 

};

5. Implement the template in a view

App.Views.User = Backbone.View.extend({
   el: "#main",
   render: function(){
    var theTemplate = template("user");	
    this.$el.html(theTemplate(this.model.toJSON()));
  }
});

6. run the render function when needed.

That is all it took and it works great.

Tagged , , , , ,