1

Does the underscore.js template support objects within objects?

For instance, I have an object rendered such as below:

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>

What do I put in place of the ??? in order to get the name of the pet?

Note: I've tried pet.name and pet[name], but both don't work. Out of ideas!

4
  • which parentheses? I assume the ones inside the object? I'm declaring an object within an object Commented Jun 7, 2013 at 3:20
  • 1
    These: pet:([name: 'fido' type: 'dog']) can't it be just pet:[name: 'fido' type: 'dog']? Also why new Object? Commented Jun 7, 2013 at 3:21
  • oops yes i can be :). I've made the edits Commented Jun 7, 2013 at 3:23
  • 1
    that was a close one, but please avoid using varnames like that, object is almost a reserved word Commented Jun 7, 2013 at 3:47

1 Answer 1

1

I see you have some syntax error there, this is the problem. You're confusing arrays with objects, and you're missing commas:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I realized I was declaring an array of objects, and objects within objects, and it carried over to my code here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.