Search code examples
javascriptdust.js

DustJS infinite nesting


I want to create a recursive template such that it handles all of the children - no matter how deep.

Lets say my context looks like

{
  div:true
  ,id:'root'
  ,children:[
    {div:true,id='root-1'}
    ,{div:true,id='root-2', children:[
      {div:true,id='root-2.1'} //etc,ect...      
     ]}
    }
}

I would like to say:

var div_tpl='{#div}'+
  '<div{#id} id="{id}"{/id}{#class} class="{class}"{/class}>'+
  '{#children}{>div_tpl/}{/children}'+ //self-ref here
  '</div>{/div}';

dust.compile(div_tpl,'div_tpl');

But of course that hangs when I feed it data. I also tried with div_tpl1 and div_tpl2, each referencing the other. So now I just need confirmation that it is 'not possible'.


Solution

  • The good news is that this is possible. It appears that the trouble you are having has to do with the way Dust does lookups. Currently, {#children} will look in the current context, and then (if it doesn't find anything in the current context) in all parent contexts.

    So, in your example, Dust would start rendering the first div (id="root"), then find it's children, and start rendering them. It would render the second div (id="root-1"), then look for children. It would not find children in the current context, so it would look in the parent context, where it would find children. Dust would then render the second div again, search for children again, and loop infinitely.

    You can avoid the infinite loop by using dot-notation:

    ...
    {#.children}
        {>div_tpl/}
    {/.children}
    ...
    

    For a working example, see this jsfiddle.