Mustache + Nested Objects

I am trying to create a tree from a list of tags that have tags inside.

Here is a JSON example that I use:

{ "tags": [{"name":"My first tag", "tags": [{"name":"My first tag inside a tag"}, {"name":"My second tag inside a tag"}] }] } 

If I use the following mustache pattern, it detects β€œMy first tag” without any problems:

 <ul> {{#tags}} <li tag-id="{{id}}"> {{name}} </li> {{/tags}} </ul> 

But then, using the following template, I try to display the tags inside this first tag:

 <ul> {{#tags}} <li tag-id="{{id}}"> {{name}} <div> {{#tags}} <a>{{name}}</a> {{/tags}} </div> </li> {{/tags}} </ul> 

Using this template, Mustache does not display anything.

How to display nested lists using Mustache?

+6
source share
1 answer

To solve this problem, I will do:

 <div id="result-tag"></div> <script language="javascript" type="text/javascript"> function test(){ var view = { "tags": [{"name":"My first tag", "tags": [{"name":"My first tag inside a tag"}, {"name":"My second tag inside a tag"}] }] }; var templt = '<ul>{{#tags}}<li>{{name}}<div>{{>subtags}}</div></li>{{/tags}}</ul>'; var partials = {"subtags": "{{#tags}}<a>{{name}}</a><br/>{{/tags}}"}; var html = Mustache.to_html(templt, view, partials); document.getElementById('result-tag').innerHTML=html; } window.onload = test; </script> 

I hope this helps

+7
source

Source: https://habr.com/ru/post/905149/


All Articles