我不知道我在这个模板中做错了什么。
这是我的数据:
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
包装在 context/params var 中,例如:
var content = _.template(template, {movies: movies});
关于javascript - 使用下划线循环遍历集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953344/