Handlebars.js的递归布局

ant*_*lma 8 javascript templates json

我有一个简单的对象层次结构,包括:

Category
 String name
 List childCategories;
Run Code Online (Sandbox Code Playgroud)

我想以通用方式使用把手来表示这种布局,但我无法理解如何嵌套布局.鉴于此布局:

<script id="categories-template" type="text/x-handlebars-template">
    {{#categories}}
        <ul >
            <li>                    
                <span>{{name}}</span>       
                <div>{{#childCategories}}{{/childCategories}}</div>
            </li>       
        </ul>
    {{/categories}}
</script>
Run Code Online (Sandbox Code Playgroud)

为所有子类别重用现有类别模板的最佳方法是什么?是否有必要注册处理程序?有没有更简单的方法?

小智 16

两个模板

<!-- language: html -->

<script id="categories-template" type="text/x-handlebars-template">
{{#categories}}
    <ul >
       <li>                    
          <span>{{name}}</span>       
          {{#if childCategories}}                    
             <div>{{&testHelper childCategories}}</div>
          {{/if}}
       </li>       
    </ul>
{{/categories}}
</script>

<script id="categories-nested" type="text/html">
    {{&testHelper categories}}
</script>
Run Code Online (Sandbox Code Playgroud)

还有一个把手助手

Handlebars.registerHelper('testHelper', function(info) {
    var template = Handlebars.compile($('script#categories-template').html());
    return template(categories);
});
Run Code Online (Sandbox Code Playgroud)


kir*_*oid -2

<script id="categories-template" type="text/x-handlebars-template">
    <ul>
    {{#each categories}}
        <li>                    
            <span>{{name}}</span>       
            <div>
                <ul>
                    {{#each childCategories}}
                        <li><!-- content: blah-blah-blah --></li>
                    {{/each}}
                </ul>
            </div>
        </li>
    {{/each}}
    </ul>
</script>
Run Code Online (Sandbox Code Playgroud)

  • 好吧,这会让我深入一层,但是子类别也可能有子类别等等,所以我真的需要它来重用整个布局,如果你明白我的意思的话 (3认同)