Underscore rendering [object HTMLDivElement]

五迷三道 提交于 2020-01-11 07:39:19

问题


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

回答1:


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.




回答2:


Underscore Template Editor might be of some help to start with.




回答3:


If it is from another view I use .html() or .outerHTML like this:

otherview: view.render().$el.html()
otherview: view.render().el.outerHTML


来源:https://stackoverflow.com/questions/20291756/underscore-rendering-object-htmldivelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!