I'm trying to create a tree from a list of tags which have tags inside them.
Here's a sample of the JSON I'm using :
{
  "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 template, it displays "My first tag" without any problems :
<ul>
{{#tags}}
<li tag-id="{{id}}">
  {{name}}
</li>
{{/tags}}
</ul>
But then, using the following template, I'm trying 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 doesn't render anything.
How do I display nested lists using Mustache?
To solve that issue, 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 that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With