2

我有一个使用 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# 中实现相同的功能?

4

2 回答 2

1

修改tpl如下图!

var tpl = "{{employee}}<li>{{firstName}} {{lastName}}</li>{{/employee}}{{#depts}}<h1>{{name}}</h1>" +
      "<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";

然后传递您的对象数组。它会正确获取。!!!

于 2013-04-30T06:08:21.600 回答
1

我知道这是一个老问题,但我发现有一种方法可以满足您的要求。Nustache 允许使用 < 符号创建模板或部分内联,因此 {{>employee}}此处的部分模板 {{/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}}

所以你在 nastache 中的新代码将是:

    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}}
于 2014-11-20T03:46:41.993 回答