Mustache JS, How to create a recursive list with an unknown number of subscriptions?

I saw how this was discussed in several threads, and it looks like it was (or is) a way to do this. But I can't get this to work. So something is missing me.

The result should look

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

I get

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

What am i still


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/

In any case, I thought the mustache would recursively create helper lists based on the original template. But it seems to me that I should create an entire nested HTML structure to make it generate HTML for the next levels.

So what should I do a template for each level? What am I missing, that I only get the first sub-level and not the second? Or is it simply impossible with a Mustache?

+7
javascript recursion mustache
source share
1 answer

What you are missing is that the rendering of this type of menu should be recursive. Therefore, you need to reference the template inside the template itself. Fortunately, mustaches have this capability through the construction of partials . So you can write something like this:

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

However, since Mustache will always go up the hierarchy of nodes in the object graph, it will always find a menu item for rendering, so this will cause an endless loop with your data. Therefore, an additional change to your data is necessary:

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

Note the extra line "menu": null . This will cause Usachi to stop recursing when it sees it.

I updated the script with these changes: https://jsfiddle.net/6g7wz5vL/24/ .

+10
source share

All Articles