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 = ""

	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");	

6. run the render function when needed.

That is all it took and it works great.

Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: