I’m following along with this tutorial (in french only) https://github.com/k33g/articles/blob/master/2011-08-14-BB-VIEWS.md which uses underscore templates with Backbonejs.
The tutorial says to put this template below in index file.
<script type="text/template" id="doc-template">
<span><%= id %></span>
<span><%= title %></span>
<span><%= test %></span>
<span><%= keywords %></span>
</script>
<div id='doc-container'></div>
I’m putting it in index.html.erb, however, the tutorial author is not using rails. It’s necessary for me to use erb because I also include page specific content using rails content_for helpers.
When I try to view the page, I get an undefined local variable or method error
undefined local variable or method `id' for #<#<Class:0x007fd9c3a133b8>:0x007fd9c5066d90>
If I remove those variables from the templates it’s still not rendering content to the page.
Can anyone explain what I’m doing wrong to render the data?
Other Backbone view related code
The tutorial initializes and renders a view in the appropriate container…
el : $('#doc-container'),
initialize : function() {
this.template = _.template($('#doc-template').html());
_.bindAll(this, 'render');
this.model.on('change', this.render);
},
render : function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
Update
I’m having the same problem when I follow the tutorials instructions for a collection view. It throws an error for underscore’s each method
undefined local variable or method `_' for #<#<Class:0x007fd9c3a133b8>:0x007fd9c2c78a78>
template in index.html.erb
<script type="text/template" id="docs-collection-template">
<ol>
<% _.each(docs, function(doc) { %>
<li><%= doc.id %> : <%= doc.title %></li>
<% }); %>
</ol>
</script>
The problem is that Underscore is using the same syntax for templating as ERB, so it is conflicting. You need to tell Underscore to use a different syntax. From the Underscore docs:
So, somewhere in your JavaScript code, before you compile the template, add the following code:
Then, anywhere in your template where you have
<% %>, change it to{{ }}, change<%= %>to{{= }}, and change<%- %>to{{- }}.