Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in the Rails framework should I place my Backbone templates?

I'm a rails developer trying to learn Backbone and then I ran into this problem: since Underscore templates include symbols like <%=%>, I guess templates can't be included into erb files, so is it okay to have a rails partial for every single template? And what extension should it be?

like image 268
Erik Escobedo Avatar asked Nov 15 '11 14:11

Erik Escobedo


2 Answers

You can escape the erb symbols by using two % in the opening tag, and put your backbone templates in the rails views:

<script type='text/template' id="my-template'>
  <%%= name %>
</script>

will output the following in your page:

<script type='text/template' id="my-template'>
  <%= name %>
</script>

Putting your Backbone templates directly in your rails views is IMHO the best option when you're trying to learn. You're already wrestling with the new concepts, no need to add another hurdle.

like image 136
Benoit Garret Avatar answered Nov 15 '22 01:11

Benoit Garret


Starting with Rails 3.1, it provides two things that make working with Backbone templates a little easier: the asset pipeline, and automatic JST (JavaScript Template) compilation.

Create a directory in your app/assets folder called templates. This directory will automatically be picked up by the asset pipeline.

Next, name the files in that directory with an extension of jst and the type of template you are creating ejs (embedded javascript). You can even nest them in directories. For example:

app/assets/templates/my_template.jst.ejs
app/assets/templates/bookmarks/show.jst.ejs

The asset pipeline also allows you to use other templating languages like embedded coffeescript, mustache, handlebars, etc. by simply changing the file extension (and including any necessary gems).

Now to reference your JST templates in your Backbone views, simply use the path to the filename:

var Bookmark = Backbone.View.extend({
  template: JST['bookmarks/show'],
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

You may need to add this line to your application.js:

// require_tree ../templates

Here's a nice article which explains all of this in a little more detail: http://www.bigjason.com/blog/precompiled-javascript-templates-rails-3-1

like image 32
Andrew Avatar answered Nov 15 '22 01:11

Andrew