Underscore rendering [object HTMLDivElement]

南楼画角 提交于 2019-12-01 14:34:36

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.

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

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

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