最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mustache + nested objects - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 4, 2012 at 22:33 Benjamin NetterBenjamin Netter 1,5514 gold badges18 silver badges34 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

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

发布评论

评论列表(0)

  1. 暂无评论