我在这个 Javascript/JSON/Handlebars 事情上是全新的,我无法让一个具有两个嵌套级别的 JSON 对象在 Handlebars 模板中工作。
我已经用 JSONLint 验证了 JSON 对象,所以它是有效的 JSON 代码,但我不知道我是否有正确的 JSON 格式来使模板正常工作。:) (我在另一个系统中手动构建 JSON。)或者可能是模板的语法不正确。这就是我希望找到的...
简短描述:这个对象是一个目录。我有章节,然后是每个章节中的电影。所以电影是每个章节元素的嵌套元素。
我想要类似于以下内容的 HTML 输出:
Chapter1: ChapterName
Movie1: MovieName
Movie2: MovieName
Chapter2: Chaptername
Movie1: MovieName
Movie2: MovieName
Movie3: MovieName
我似乎只得到了 1 个数据实例(我的 JSON 对象中的最后一个元素),或者我什么也得不到。(取决于我尝试的小调整或版本。)浏览器控制台没有显示任何错误。
这是迄今为止我一直在尝试使用的所有代码(脚本、HTML、模板等):
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8">
<title>Handlebars Demo</title>
<!-- dependant files -->
<script src="Handlebars.js"></script>
</head>
<!-- template -->
<script id="template2" type="text/x-handlebars-template">
<div>Chapter stuff:</div>
<ul>{{#each Chapter}}
<ol>{{@index}} {{ChapterName}}
{{#each movies}}
<li>Movie ID:{{movieIDnum}}</li>
{{/each}}
</ol>
{{/each}}
</ul>
</script>
<body><div id="main"></div></body>
<script>
var source = document.getElementById('template2').innerHTML;
var template = Handlebars.compile(source);
var data = {
"Chapter" : {
"ChapterName" : "Introduction",
"chapterNum" : "1",
"movies" : [
{
"movieIDnum" : "16244028",
"movieName" : "Update Test Movie 0",
"movieFileName" : "Test0.mov",
"moviePositionInChapter" : "1"
}
]
},
"Chapter" : {
"ChapterName" : "Welcome",
"chapterNum" : "2",
"movies" : [
{
"movieIDnum" : " 17322365",
"movieName" : "Update Test movie 1",
"movieFileName" : "Test1.mov",
"moviePositionInChapter" : "1"
},
{
"movieIDnum" : " 17326267",
"movieName" : "Update Test movie 3",
"movieFileName" : "Test3.mov",
"moviePositionInChapter" : "2"
}
]
},
"Chapter" : {
"ChapterName" : "The new Interface",
"chapterNum" : "2",
"movies" : [
{
"movieIDnum" : " 1732123476",
"movieName" : "Update Test movie 12",
"movieFileName" : "Test12.mov",
"moviePositionInChapter" : "1"
},
{
"movieIDnum" : " 173262373",
"movieName" : "Update Test movie 9",
"movieFileName" : "Test9.mov",
"moviePositionInChapter" : "2"
},
{
"movieIDnum" : " 173273474",
"movieName" : "Update Test movie 10",
"movieFileName" : "Test10.mov",
"moviePositionInChapter" : "3"
}
]
},
"Chapter" : {
"ChapterName" : "What is an Update?",
"chapterNum" : "4",
"movies" : [
{
"movieIDnum" : " 177342131",
"chapterNum" : "4",
"chapterName" : "What is an Update?",
"movieName" : "Test movie again",
"movieFileName" : "Test13.mov",
"moviePositionInChapter" : "1"
}
]
},
"Chapter" : {
"ChapterName" : "Editing",
"chapterNum" : "5",
"movies" : [
{
"movieIDnum" : " 173290878",
"movieName" : "Update Test movie 14",
"movieFileName" : "Test14mov",
"moviePositionInChapter" : "1"
},
{
"movieIDnum" : " 177344914",
"movieName" : " Movie 15 Test",
"movieFileName" : "Test233.mov",
"moviePositionInChapter" : "2"
}
]
}
}
var result = template(data);
document.write(result);
</script>
</html>
我想知道为什么这不起作用,而不仅仅是“以下是如何使用 4 种完全不同格式的其他不同事物来解决您的问题”。据我了解,这应该可以与我尝试使用的工具一起使用。我想更好地理解这些工具并从过程中学习,而不仅仅是获得解决方案。(你知道,教一个人钓鱼...... :))
谢谢,J