【问题标题】:Recursive layouts with Handlebars.jsHandlebars.js 的递归布局
【发布时间】:2012-03-12 22:00:26
【问题描述】:

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

Category
 String name
 List childCategories;

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

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

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

【问题讨论】:

    标签: javascript json templates


    【解决方案1】:

    两个模板

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

    还有一个把手助手

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

    【讨论】:

    • 当我开始使用 HB 来获取嵌套模板时,我使用了它,现在我发现了部分模板。有区别吗?
    【解决方案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>
    

    【讨论】:

    • 嗯,这会让我更深一层,但子类别也可能有子类别等等,所以如果你明白我的意思,我真的需要它来重用整个布局
    • 嗯。然后使用该答案:stackoverflow.com/questions/8044919/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2012-06-15
    相关资源
    最近更新 更多