Search code examples
javascriptbackbone.jsunderscore.jsunderscore.js-templating

Underscore rendering [object HTMLDivElement]


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) );
  },

Solution

  • 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.