繁体   English   中英

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

[英]Recursive Handlebars.js Template. How to determine the depth?

经过数小时的搜索,我找不到适合我问题的正确答案。 我想随手把显示任意树深。 有一个很好的小提琴示例,用于在把手中进行递归模板化( https://jsfiddle.net/adamboduch/5yt6M/ ),但我无法理解树的细节。 @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 margin left或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"

我怀疑使用“把手局部”无法完成此操作。 递归助手可以解决这个问题。 我已经使用您之前链接的小提琴作为此处的最小概念证明的基础。 您可以更新以使用自己的数据结构和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}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM