我正在关注 Dave Ward 的这篇文章 (http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/) 为博客加载复合模板,我在其中一篇博文总共有 3 个小模板(全部在一个文件中)。在模板文件中,我有这 3 个模板:
- blogTemplate,我在其中呈现“ postTemplate ”
- 在“postTemplate”中,我想渲染另一个显示评论的模板,我称之为“ commentsTemplate ”
- “评论模板”
这是我的json数据的结构:
blog
Title
Content
PostedDate
Comments (a collection of comments)
CommentContents
CommentedBy
CommentedDate
目前,我可以使用以下代码呈现 Post 内容:
Javascript
$(document).ready(function () {
$.get('/GetPost', function (data) {
$.get('/Content/Templates/_postWithComments.tmpl.htm', function (templates) {
$('body').append(templates);
$('#blogTemplate').tmpl(data).appendTo('#blogPost');
});
});
});
模板
<!--Blog Container Templates-->
<script id="blogTemplate" type="x-jquery-tmpl">
<div class="latestPost">
{{tmpl() '#postTemplate'}}
</div>
</script>
<!--Post Item Container-->
<script id="postTemplate" type="x-jquery-tmpl">
<h2>
${Title}</h2>
<div class="entryHead">
Posted in <a class="category" rel="#">Design</a> on ${PostedDateString} <a class="comments"
rel="#">${NumberOfComments} Comments</a></div>
${Content}
<div class="tags">
{{if Tags.length}} <strong>Tags:</strong> {{each(i, tag) Tags}} <a class="tag" href="/blog/tags/{{= tag.Name}}">
{{= tag.Name}}</a> {{/each}} <a class="share" rel="#"><strong>TELL A FRIEND</strong></a>
<a class="share twitter" rel="#">Twitter</a> <a class="share facebook" rel="#">Facebook</a>
{{/if}}
</div>
<!-- close .tags -->
<!-- end Entry 01 -->
{{if Comments.length}}
{{each(i, comment) Comments}}
{{tmpl() '#commentTemplate'}}
{{/each}}
{{/if}}
<div class="lineHor">
</div>
</script>
<!--Comment Items Container-->
<script id="commentTemplate" type="x-jquery-tmpl">
<h4>
Comments</h4>
<!-- COMMENT -->
<div id="authorComment1">
<div id="gravatar1" class="grid_2">
<!--<img src="images/gravatar.png" alt="" />-->
</div>
<!-- close #gravatar -->
<div id="commentText1">
<span class="replyHead">by<a class="author" rel="#">${= comment.CommentedBy}</a>on today</span>
<p>
{{= comment.CommentContents}}</p>
</div>
<!-- close #commentText -->
<div id="quote1">
<a class="quote" rel="#"><strong>Quote this Comment</strong></a>
</div>
<!-- close #quote -->
</div>
<!-- close #authorComment -->
<!-- END COMMENT -->
</script>
我遇到问题的地方是
{{each(i, comment) Comments}}
{{tmpl() '#commentTemplate'}}
{{/each}}
更新 - 调用 GetPost 方法时的示例 Json 数据
{
Id: 1,
Title: "Test Blog",
Content: "This is a test post asdf asdf asdf asdf asdf",
PostedDateString: "2010-12-20",
- Comments: [
- {
Id: 1,
PostId: 1,
CommentContents: "Test comments # 1, asdf asdf asdf",
PostedBy: "User 1",
CommentedDate: "2010-12-20"
},
- {
Id: 2,
PostId: 1,
CommentContents: "Test comments # 2, ghjk gjjk gjkk",
PostedBy: "User 2",
CommentedDate: "2010-12-21"
}
]
}
我尝试过传入{{tmpl(comment) ...
,{{tmpl(Comments) ...
或 leave{{tmpl() ...
但似乎没有任何效果。我不知道如何遍历Comments集合并将该对象传递给commentsTemplate。
有什么建议么?
非常感谢。