简体   繁体   中英

Recursive layouts with Handlebars.js

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?

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.compile($('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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM