Underscore rendering [object HTMLDivElement]

后端 未结 3 1395
旧时难觅i
旧时难觅i 2021-01-16 17:52

I have an underscore template that is appending the following text \"[object HTMLDivElement]\" , but it\'s supposed to append value that \"model.get(\'title

相关标签:
3条回答
  • 2021-01-16 18:33

    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.

    0 讨论(0)
  • 2021-01-16 18:42

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

    otherview: view.render().$el.html()
    otherview: view.render().el.outerHTML
    
    0 讨论(0)
  • 2021-01-16 18:46

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

    0 讨论(0)
提交回复
热议问题