underscore.js模板是否支持对象中的对象?
例如,我有一个如下所示的对象:
var person = new Person([
{name: 'Allen', pet:[ name: 'fido', type: 'dog']},
{name: 'Chris', pet:[ name: 'garfield', type: 'cat']}
]);
<script type="text/template" id="template">
<%=name%> has a pet named <%= ??? %>
</script>
为了获得宠物的名字,我应该用什么代替 ??? ?
注意:我已尝试pet.name
和pet[name]
,但两者均无效。出于创意!
答案 0 :(得分:1)
我发现你有一些语法错误,这就是问题所在。您将数组与对象混淆,并且您缺少逗号:
var data = { name: 'Allen', pet: { name: 'fido', type: 'dog' } };
var template = _.template('<%=name%> has a pet named <%=pet.name%>', data);
console.log(template); //=> Allen has a pet named fido