3

On the Underscore.js site, we're given the code example:

var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people: ['moe', 'curly', 'larry']});

=> "<li>moe</li><li>curly</li><li>larry</li>"

Lets assume that I want to pass 2 array of values instead of 1 (@ people). So that I could do something like:

{ %> <li><%= name %> , <%= address %></li> <% }

I tinkered around for a bit and wasn't sure how to use the method for this.

user1413969
  • 1,261
  • 2
  • 13
  • 25
  • You mean an array of names and an array of adresses? Better pass an array of objects. – Bergi Jul 29 '14 at 17:36
  • possible duplicate of [How to use underscore.js as a template engine?](http://stackoverflow.com/questions/4778881/how-to-use-underscore-js-as-a-template-engine) – Evan Davis Jul 29 '14 at 17:41

1 Answers1

4

I believe you'd have to make the array into an array of objects with "name" and "address" properties:

_.template(list, {people: [ 
    { name: 'moe', address: 'foo'}, 
    { name: 'curly', address: 'bar' } 
] });

Then the parameter would be the object "person" instead of just the string "name":

var list = "<% _.each(people, function(person) { %> <li>Name: <%= person.name %>, Address: <%= person.address %></li> <% }); %>";
McGarnagle
  • 101,349
  • 31
  • 229
  • 260