MustacheJS rendering of nested JSON using partial

I'm trying to make my nested (maybe multi-level) JSON using partial parts of the Mustache. He renders only to the second level, he is not the third or more. By definition, partial parts can be used to render rendering. Am I doing it wrong? or is there any other way to achieve the same use of mustache?

Js bin

Template:

<script id="product-list" type="x-tmpl-mustache"> <ul class='products'> {{#product}} <li class='product'> {{ productName }} </li> {{> recurse }} {{/product}} {{^product}} <li class='empty'> No products Available </li> {{/product}} </ul> </script> <script id="recursive-list" type="x-tmpl-mustache"> <ul class='products'> {{#product}} <li class='product'> {{ productName }} </li> {{/product}} </ul> </script> 

Data:

 var data = { product: [{ productName: "Category1", product: [{ productName: "Windows" }, { productName: "Windows Mobile" }] }, { productName: "Category2", product: [{ productName: "SubCategory 1", product: [{ productName: "Nexus 4" }, { productName: "Nexus 6" }] }, { productName: "SubCategory 2", product: [{ productName: "ipod" }, { productName: "iphone" }] }] }] }; 

Rendering:

 $('body').html( Mustache.render( productList.html(), data, {recurse :recursiveList.html()}) ); 

Exit (missing products: Nexus 4, Nexus 5, ipod, iphone)

 Category1 - Windows - Windows Mobile Category2 - SubCategory 1 - SubCategory 2 
+6
source share
1 answer

Got a solution from the maintainer MustacheJS,

JSBin Work

I can use the product-list template because both product-list and recurisve-list are similar: $('body').html(Mustache.render(productList.html(), data, {recurse: productList.html()}));

If you do, you will get maximum call stack size exceeded , which you probably would not have expected. This is because by structuring your data and templates the way you did, you created infinite recursion. In products with a tail (for example, Nexus 4, Nexus 6, iPod, etc.), the Template will look for the product property, and not find it. This way, it will update the context stack and check each level until it finds something with the product property. You can stop this by making sure that leaf products have a product property with a value such as false, null or [] .

New data:

 var data = { product: [{ productName: "Category1", product: [{ productName: "Windows", product: null }, { productName: "Windows Mobile", product: null }] }, { productName: "Category2", product: [{ productName: "SubCategory 1", product: [{ productName: "Nexus 4", product: null }, { productName: "Nexus 6", product: null }] }, { productName: "SubCategory 2", product: [{ productName: "ipod", product: null }, { productName: "iphone", product: null }] }] }] }; 
0
source

All Articles