I have an underscore template that is appending the following text "[object HTMLDivElement]" , but it's supposed to append value that "model.get('title')" returns.
Here's my template:
<script type="text/template" id="todoTemplate">
<div class='todoBlock'>
<li class='appendedTodo'>
<%= title %>
</li>
<button class='delete'>Delete</button><p>
</div>
</script>
Here's my function:
addTodoLi: function(model){
var todoData = model.get('title');
var compileTemplate = _.template( $('#todoTemplate').html() );
$('#todo-list').append( compileTemplate(todoData) );
},
Underscore Template Editor might be of some help to start with.
Your
todoData
is (presumably) a string:but a compiled Underscore template wants a key/value object as its argument:
Looks like you have a
title
global variable orwindow
property that is a<div>
DOM object or you would get a ReferenceError complaining about an unknowntitle
variable instead of a stringified DOM object.In any case, the fix is pretty easy: give the template function what it wants:
or the common Backbone approach:
There are cases where the model will have optional attributes that the templates need to access. In such cases, you might have:
in the template but sometimes
toJSON
will give you:and other times you'll get:
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 thentoJSON
should ensure that it returns them withundefined
ornull
values.If it is from another view I use
.html()
or.outerHTML
like this: