【问题标题】:Mustache + nested objects小胡子 + 嵌套对象
【发布时间】:2012-01-04 22:33:49
【问题描述】:

我正在尝试从包含标签的标签列表中创建一棵树。

这是我正在使用的 JSON 示例:

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

如果我使用以下胡子模板,它会毫无问题地显示“我的第一个标签”:

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

然后,使用以下模板,我试图在第一个标签内显示标签:

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

使用这个模板,Mustache 不会渲染任何东西。

如何使用 Mustache 显示嵌套列表?

【问题讨论】:

    标签: javascript templates mustache


    【解决方案1】:

    为了解决这个问题,我会这样做:

    <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>
    

    希望对你有帮助

    【讨论】:

    • 我今天试试,我会回复你的!谢谢。
    • 效果很好!我实际上遇到了一个问题,因为我使用的是 $('#my-template').html() 并且它用 ">" 替换了 ">",我不得不使用 replace('>', '>')
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 2012-07-08
    • 2014-07-05
    • 2018-02-08
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多