I have an underscore template that is appending the following text \"[object HTMLDivElement]\" , but it\'s supposed to append value that \"model.get(\'title
Your todoData
is (presumably) a string:
var todoData = model.get('title');
but a compiled Underscore template wants a key/value object as its argument:
When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables.
Looks like you have a title
global variable or window
property that is a <div>
DOM object or you would get a ReferenceError complaining about an unknown title
variable instead of a stringified DOM object.
In any case, the fix is pretty easy: give the template function what it wants:
$('#todo-list').append(compileTemplate({ title: todoData }));
or the common Backbone approach:
$('#todo-list').append(compileTemplate(model.toJSON()));
There are cases where the model will have optional attributes that the templates need to access. In such cases, you might have:
<%= pancakes %>
in the template but sometimes toJSON
will give you:
{ title: 'x' }
and other times you'll get:
{ title: 'x', pancakes: 11 }
In such case you need to "un-optionalize" the optional attributes in your toJSON
: toJSON
should supply everything. If you have attributes that are optional then toJSON
should ensure that it returns them with undefined
or null
values.
If it is from another view I use .html()
or .outerHTML
like this:
otherview: view.render().$el.html()
otherview: view.render().el.outerHTML
Underscore Template Editor might be of some help to start with.