Search code examples
dust.js

Looping issue when rendering an object hierarchy using Dust.JS 2.7.2 to ul/li tags


I'm trying to render an object structure in Dust 2.7.2 such as

{
   name:"Home Page",
   url: "/",
   "sub-page1": {
        name: "Sub Page 1",
        url: "/sub-page1",
        "sub-sub-page1": {
             "name": "Sub Sub Page1",
             "url": "/sub-page1/sub-sub-page1"
        }
    }
}

to something like

<ul><li><a href="/">Home Page</a><ul><li><a href="/subpage1">Sub Page 1</a> ...

with a recursive partial, but I can't seem to loop through the variably named objects without causing an infinite loop. My current attempt looks like this, with the partial calling itself:

<li>
    <a href="{url}">{name}</a>{#.}<ul>{>"components/menu/recurlist"/}</ul>{/.}
</li>


Solution

  • There's no way for Dust to guess the name of your nested context object when it changes every time. You really need to keep the nesting structure identical at all levels. If you absolutely must, you can write custom helpers to get around that, but that's outside the scope of this question.

    Once you have normalized data, your template becomes simple:

    <ul>
      <li><a href="{url}">{name}</a>
        {#subpage}{>"components/menu/recurlist"/}{/subpage}
      </li>
    </ul>