Javascript 使用具有多个嵌套层的数据进行模板化
我正在开发一些CouchDB应用程序,这非常有趣。我还学习了如何使用Mustache.js进行模板制作。我的问题是,当您的数据有许多嵌套层时,模板化的最佳方法是什么。下面是一个例子:Javascript 使用具有多个嵌套层的数据进行模板化,javascript,json,couchdb,mustache,Javascript,Json,Couchdb,Mustache,我正在开发一些CouchDB应用程序,这非常有趣。我还学习了如何使用Mustache.js进行模板制作。我的问题是,当您的数据有许多嵌套层时,模板化的最佳方法是什么。下面是一个例子: var jsondata = { post1: { title: "First blog post", author: "John", tags: ["awesome", "interesting", "philosophical"], comments: { jul
var jsondata = {
post1: {
title: "First blog post",
author: "John",
tags: ["awesome", "interesting", "philosophical"],
comments: {
julie: "I love it!",
mark: "I hate it!"
}
},
post2: {
title: "Second blog post",
author: "Jill",
tags: ["extraordinary", "crazy", "nice"],
comments: {
julie: "I love it!",
mark: "I hate it!"
}
};
我意识到这取决于数据的独特结构,但是有一种通用的方法可以很好地工作吗?以下是我正在考虑的一些问题:
- 从集合中提取嵌套数据,以便拥有顶级数组的集合,然后使用辅助函数将这些数组编译为模板
- 构建镜像数据的模板,然后使用$each、模板和正则表达式的疯狂组合一次性编译模板
- 将编译分解为多个部分,然后多次遍历模板,直到完全完成
PS:我正计划将博客文章、评论和标签分离成单独的json文档,然后将它们与couchdb视图和列表一起,因此我仍然对结果数据结构有点不确定。首先,您可以使用现有的内容,只需稍加修改(为了呈现注释,您需要有一个已知的键)。如果您可以更改要传递给引擎的数据,您可以执行以下操作:
<script type="text/javascript">
$(function () {
var posts = {blogs:[
{
title:"First blog post",
author:"John",
tags:["awesome", "interesting", "philosophical"],
comments:[
{name:"juli", comment:"I love it"},
{name:"foo", comment:"bar"}
]
},
{
title:"Second blog post",
author:"Jill",
tags:["extraordinary", "crazy", "nice"],
comments:[
{name:"juli", comment:"I love it"},
{name:"foo", comment:"bar"}
]
}
]};
var template = $("#template").html();
var output = Mustache.render(template, posts);
console.log(output);
});
</script>
<script id="template" type="x-template">
{{#blogs}}
<div>{{title}}</div>
<div>{{author}}</div>
<ul>
{{#tags}}
<li>{{.}}</li>
{{/tags}}
</ul>
<ul>
{{#comments}}
<li>{{name}}: {{comment}}</li>
{{/comments}}
</ul>
{{/blogs}}
</script>
包含有关使用分部的更多信息。首先,您可以使用现有的内容,只需稍加修改即可(为了呈现注释,您需要有一个已知的键)。如果您可以更改要传递给引擎的数据,您可以执行以下操作:
<script type="text/javascript">
$(function () {
var posts = {blogs:[
{
title:"First blog post",
author:"John",
tags:["awesome", "interesting", "philosophical"],
comments:[
{name:"juli", comment:"I love it"},
{name:"foo", comment:"bar"}
]
},
{
title:"Second blog post",
author:"Jill",
tags:["extraordinary", "crazy", "nice"],
comments:[
{name:"juli", comment:"I love it"},
{name:"foo", comment:"bar"}
]
}
]};
var template = $("#template").html();
var output = Mustache.render(template, posts);
console.log(output);
});
</script>
<script id="template" type="x-template">
{{#blogs}}
<div>{{title}}</div>
<div>{{author}}</div>
<ul>
{{#tags}}
<li>{{.}}</li>
{{/tags}}
</ul>
<ul>
{{#comments}}
<li>{{name}}: {{comment}}</li>
{{/comments}}
</ul>
{{/blogs}}
</script>
包含有关使用部分的更多信息。非常有用!必须知道密钥的前提非常大。我可以使用纯JavaScript调整数据,以便知道密钥。您只在两个位置调整了数据,对吗?博客和评论?谢谢!!非常有用!必须知道密钥的前提非常大。我可以使用纯JavaScript来调整我的数据,以便知道密钥。您只在两个位置调整了数据,对吗?博客和评论?谢谢!!