Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache + nested objects

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?

like image 610
Benjamin Netter Avatar asked Jan 04 '12 22:01

Benjamin Netter


1 Answers

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

like image 167
Givius Avatar answered Sep 24 '22 17:09

Givius