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

javascript - Recursive layouts with Handlebars.js - Stack Overflow

programmeradmin4浏览0评论

I have a simple object hierarchy consisting of:

Category
 String name
 List childCategories;

I would like to represent this layout using handlebars in a generic way, but I am having trouble understand how to nest layouts. Given this layout:

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

What is the best way to reuse the existing categories template for all the child categories? Is it necessary to register a handler? Is there an easier way?

I have a simple object hierarchy consisting of:

Category
 String name
 List childCategories;

I would like to represent this layout using handlebars in a generic way, but I am having trouble understand how to nest layouts. Given this layout:

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

What is the best way to reuse the existing categories template for all the child categories? Is it necessary to register a handler? Is there an easier way?

Share Improve this question asked Mar 12, 2012 at 22:00 ant-depalmaant-depalma 2,0664 gold badges27 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 16

Two templates

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

And a Handlebars Helper

Handlebars.registerHelper('testHelper', function(info) {
    var template = Handlebars.pile($('script#categories-template').html());
    return template(categories);
});
<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>
发布评论

评论列表(0)

  1. 暂无评论