使用Jade创建无序列表树

3

我有一个叫做 boundedArea 的对象,它在字段 children 中包含了一个 boundedArea 对象数组,我想创建一个无序列表树。

我有以下代码:

- for (var index = 0; index < rootAreas.length; index++) {
  - var boundedArea = rootAreas[index];
  div(class='panel panel-default')
    div.panel-heading
      | #{boundedArea.NAME}
    div.panel-body
      - printChildren(boundedArea, 0); 
- }
- 
- function printChildren(boundedArea, depth) {
  - var children = boundedArea.children;
  - if (children == null || children.length == 0) {
    - return;
  - } 
  ul  
  - for (var index = 0; index < children.length; index++) {
    - var child = children[index];
    li #{child.NAME}
    - console.log("Printing %s child of %s", child.NAME, boundedArea.NAME);
    - printChildren(child, depth + 1); 
  - } 
- }

显然,这样做可以输出所有的值。然而,由于 ulli 标签具有固定的缩进,它们不会嵌套,只会按顺序打印。

是否有任何方法可以动态设置缩进级别或强制嵌套这些标签?或者我应该使用完全不同的嵌套模型。

我尝试创建一个名为 "indent" 的javascript变量,每个深度级别填充两个空格,然后尝试使用 #{indent} 但结果只是创建了带有空格的标签,这不是我想要的。虽然这表明在某种程度上,这个想法周围的东西可能有效,因为它必须在某个级别上解决,然后被视为某种标记。


你对如何将数组转换成树有什么计划?当你决定树的形式时,例如“平衡二叉树”,节点的层级可以自然地计算出来。 - Fumu 7
1个回答

2

尝试使用mixin而不是函数。Mixin会记住缩进级别(不确定为什么函数不能)。

mixin printChildren(boundedArea, depth)
  - var children = boundedArea.children;
  - if (children == null || children.length == 0)
    - return;
  ul  
    - for (var index = 0; index < children.length; index++)
      - var child = children[index];
      li #{child.NAME}
        +printChildren(child, depth + 1)

- for (var index = 0; index < rootAreas.length; index++)
  - var boundedArea = rootAreas[index];
  div(class='panel panel-default')
    div.panel-heading
      | #{boundedArea.NAME}
    div.panel-body
      +printChildren(boundedArea, 0)

我稍微修改了你的代码。使用+而不是-来调用mixin,并且它们需要在使用前先定义。

我用以下样本数据进行了测试:

{
  rootAreas: [
    {
      NAME: 'area1',
      children: [
        { NAME: 'child1' },
        { NAME: 'child2' },
        { 
          children: [
            { NAME: 'child3' },
            { NAME: 'child4' },
          ]
        },
      ]
    },
    {
      NAME: 'area2',
      children: [
        { NAME: 'child5' },
        { NAME: 'child6' },
        { NAME: 'child7' },
      ]
    }
  ]
}

模板生成了以下HTML代码:

<div class="panel panel-default">
  <div class="panel-heading">area1</div>
  <div class="panel-body">
    <ul> 
      <li>child1</li>
      <li>child2</li>
      <li>
        <ul> 
          <li>child3</li>
          <li>child4</li>
        </ul>
      </li>
    </ul>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-heading">area2</div>
  <div class="panel-body">
    <ul> 
      <li>child5</li>
      <li>child6</li>
      <li>child7</li>
    </ul>
  </div>
</div>

如果我理解得正确,这就是你要找的内容。

1
只是一个快速的提示,因为我在使用这个时遇到了语法错误:对于我来说,调用必须是+printChidlren(group, depth)+printChildren之间没有空格,末尾没有分号)。 - Florian
1
你说得对。正在编辑答案...谢谢@Florian! - JME

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接