Costa Michailidis
Costa Michailidis

Reputation: 8178

loop through collection with underscore

I can't figure out what I'm doing wrong in this template.

Here's my data:

  var movies = [
  {
    "title": "The Matrix",
    "characters": ['neo', 'trinity', 'morpheous', 'agent smith'],
    "year": 2001
  },
  {
    "title": "The Simpsons Movie",
    "characters": ['homer', 'marge', 'bart', 'lisa', 'maggie'],
    "year": 20010
  }
];

Here's my template:

<script id="template" type="template/underscore">
<% _.each(movies, function (movie) { %>
  <h1><%-title%></h1>
  <ul>
    <% _.each(characters, function(name) { %>
      <li><%-name%></li>
    <% }); %>
  </ul>
  <p><%-year%></p>
<% }); %>
</script>

And here's the compilation:

var template = $.trim( $('#template').html() );
var content = _.template(template, movies);
console.log(content);

I'm getting the error: movies is not defined. Any help would be awesome!

Upvotes: 2

Views: 2343

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 146014

The template can't "see" the fact that your context variable is named "movies". You need to pass an object with an actual property named "movies".

var context = {movies: movies};
var content = _.template(template, context);

Upvotes: 1

jmlnik
jmlnik

Reputation: 2887

The template is looking for the key 'movies' in your parameters but isn't finding it! You need to wrap movies in a context/params var, eg:

var content = _.template(template, {movies: movies});

Upvotes: 2

Related Questions