我有一个使用Nustache的Windows应用程序。我可以使用Nustache迭代一个对象或数组,但是如何使用Nustache进行部分枚举?
检查样本11.
var data = { depts: [
{ name: "Engineering",
employees: [
{firstName: "Christophe", lastName: "Coenraets"},
{firstName: "John", lastName: "Smith"}]
},
{ name: "Sales",
employees: [
{firstName: "Paula", lastName: "Taylor"},
{firstName: "Lisa", lastName: "Jones"}]
}] };
var tpl = "{{#depts}}<h1>{{name}}</h1>" +
"<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";
var partials = {employee:"<li>{{firstName}} {{lastName}}</li>"};
var html = Mustache.to_html(tpl, data, partials);
$('#sampleArea').html(html);
如何在C#中实现相同的目标?
答案 0 :(得分:1)
修改tpl,如下所示!
var tpl = "{{employee}}<li>{{firstName}} {{lastName}}</li>{{/employee}}{{#depts}}<h1>{{name}}</h1>" +
"<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";
然后传递你的对象数组。它会正常取得。!!!
答案 1 :(得分:1)
我知道这是一个老问题,但我发现有办法做你要问的事。 Nustache允许使用&lt;创建模板或部分内联。符号所以{{&gt; employee}}您的部分模板{{/ employee}}将是您的部分,然后当您想要引用它时,只需使用&gt;符号,例如:{{&gt; employee}}
来自readme.txt文件
64 {{<foo}}This is the foo template.{{/foo}}
65 The above doesn't get rendered until it's included
66 like this:
67 {{>foo}}
所以你在nustache中的新代码将是:
string tpl = "{{<employee}}<li>{{firstName}} {{lastName}}</li>{{/employee}}" +
"{{#depts}}<h1>{{name}}</h1><ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";
string html = Nustache.Core.Render.StringToString(tpl, data);
使用这种技术允许递归模板渲染,以下将呈现和部门和员工的层次结构
{{<employee}}<li>{{firstname}} {{lastname}}{{>dept}}</li>{{/employee}}
{{<dept}}
<ul>
<li >
<span >{{name}}</span>
{{#employees}}
{{>employee}}
{{/children}}
</li>
</ul>
{{/dept}}{{>dept}}