递归 Handlebars.js 模板。如何确定深度?

Recursive Handlebars.js Template. How to determine the depth?

经过几个小时的搜索,我找不到我的问题的正确答案。我有一个任意的树深度,我想用车把显示。在 handlebars ( https://jsfiddle.net/adamboduch/5yt6M/ ) 中有一个很好的递归模板示例 fiddle 但我无法获得树的深度。 @index 只告诉我每个元素的位置。

我的部分模板:

<script id="teamspeak_channel_recursive" type="text/x-handlebars-template">
   {{#each childChannel}}
   <tr class="viewer-table-row">
     <td class="viewer-table-cell">
       <span></span>
       <span class="viewer-label">{{name}}</span>
       <span></span>
     </td>
   </tr>
        {{#if childChannel}}
        {{> teamspeak_channel_recursive}}
        {{/if}}
    {{/each}}
 </script>

我想通过 css 左边距或 css class 来根据 deph 来命名名称。我也尝试过使用参数,但不允许计算数字或做任何数学运算。数学助手也没有帮助。 Javascript 据我所知,模板内部是禁止的。

<script id="teamspeak_channel_recursive" type="text/x-handlebars-template">
   {{#each childChannel}}
   <tr class="viewer-table-row">
     <td class="viewer-table-cell">
       <span></span>
       <span class="viewer-label">{{name}}</span>
       <span></span>
     </td>
   </tr>
        {{#if childChannel}}
        {{> teamspeak_channel_recursive deph=({{../deph}}+1) }} <- dosen't work only statc values or the context itself is working
        {{/if}}
    {{/each}}
 </script>

简而言之,我被卡住了,除了使用有序列表并将显示模式设置为 tablecell 之外,我没有找到出路。但这不是我想要的。同样在上下文上迭代以在之前添加递归级别也不是一个好的选择。

模型(不完整):

type": "channel",
"childChannel": 
[
{
    "type": "channel",
    "childChannel": 
[
        {
            "type": "channel",
            "childChannel": null,
            "childClient": null,
            "name": "AFK Area"
        }
    ],
    "childClient": null,
    "name": "WoW / SWToR / GuildWars2 hype"
},
{
    "type": "channel",
    "childChannel": 
[
            {
                "type": "channel",
                "childChannel": null,
                "childClient": null,
                "name": "Rumidler (AFK)"
            }
        ],
        "childClient": null,
        "name": "FPS CS:GO Hype"
    }

],
"childClient": null,
"name": "Hall of Games"

我怀疑这无法使用 Handlebars Partials 完成。不过,递归 Helper 可以解决问题。我使用您之前链接的 Fiddle 作为最小概念证明 here 的基础。您可以更新以使用您自己的数据结构和 HTML 但它基本上看起来像这样:

var listHelperOutput = '';   

function recursiveList(stuff, depth){  
    listHelperOutput += '<ul>';
    stuff.forEach(function(el){             
        listHelperOutput += '<li>';
        listHelperOutput += el.name + ' (depth ' + depth + ')';
        if (el.items){              
            recursiveList(el.items, depth + 1);            
        }
        listHelperOutput += '</li>';
    });
    listHelperOutput += '</ul>';
    return new Handlebars.SafeString(listHelperOutput);
}

Handlebars.registerHelper('listHelper', recursiveList);

并在您的模板中调用它:

{{listHelper items 1}}