使用下划线循环遍历集合

loop through collection with underscore

本文关键字:遍历 集合 循环 下划线      更新时间:2023-09-26

我不知道我在这个模板中做错了什么。

这是我的数据:

  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
  }
];

这是我的模板:

<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>

以下是汇编:

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

我得到了一个错误:电影没有定义。任何帮助都会很棒!

模板正在参数中查找关键字"movies",但找不到!您需要将movies包装在context/params-var中,例如:

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

模板无法"看到"上下文变量命名为"movies"的事实。您需要传递一个具有名为"movies"的实际属性的对象。

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