javascript - Mustache JS, How to create a recursive list with an unknown number of sub lists? -


i have seen discussed in few threads , looked (or is) way this. can't seem work. must missing something.

output should like

<ul>   <li>parent      <ul>         <li>           sub child           <ul>             <li> sub sub child</li>           </ul>        </li>      </ul>   </li> </ul> 

what is

<ul>   <li>parent      <ul>         <li>           sub child        </li>      </ul>   </li> </ul> 

what have far


template

<script type="text/template" id="template">     <ul class="parent">         {{#menu}}         <li>          {{item}}          <ul class="popupmenu">             {{#menu}}            <li>{{item}}</li>            {{/menu}}         </ul>                     </li>         {{/menu}}     </ul> </script> 

js

var data = {     menu : [{         "item" : "parent",         "menu" : [{             "item": "sub child",             "menu": [{                 "item" : "sub sub child"               }]          }]     }] };  var template = $("#template").html();  var rendered = mustache.render(template, data); $("body").html(rendered); 

fiddle

https://jsfiddle.net/6g7wz5vl/22/

anyways, thought mustache recursively create sub lists based off of initial template. seems have create entire nested html structure generate html next levels.

so have template each level? missing first sub level , not second? or not possible mustache?

what missing rendering of type of menu has recursive. need reference template inside template itself. luckily mustache has capability via partials construct. can write follows:

var rendered = mustache.render(template, data, {     "recurse": "<ul class=\"submenu\">{{#menu}}<li>{{item}}{{>recurse}}{{/menu}}</ul>" }); 

however because mustache go hierarchy of nodes in object graph, find "menu" element render, cause infinite loop data. additional change data necessary so:

var data = {     menu : [{         "item" : "parent",         "menu" : [{             "item": "sub child",             "menu": [{                 "item" : "sub sub child",                 "menu": null             }]          }]     }] }; 

note "menu": null line here. cause mustache terminate recursion when sees this.

i have updated fiddle these changes: https://jsfiddle.net/6g7wz5vl/24/.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -