简体   繁体   中英

Recursive partials with Handlebars.js and require.js

I am trying to render a hierarchy of nodes using Handlebars. I use require.js and the plugin for Handlebars to pull the relevant templates. My attempts at calling a partial recursively fail miserably.

sample data

var data = {
    nodes: [
        {
            title: "node 1",
            nodes: [
                {title: "node 1-1"},
                {title: "node 1-2"}
            ]
        },
        {
            title: "node 2"
        }
    ]
};

require call

require(['hbs!templates/linker/sub'], function(tpl) {
    console.log(tpl(data));
});

basic template
templates/linker/sub

{{#if nodes}}
<ul>
    {{#each nodes}}
        <li>{{title}}
        </li>
    {{/each}}
</ul>
{{/if}}

output (success)

<ul>
   <li>node 1</li>
   <li>node 2</li>
</ul>

template with partial
templates/linker/sub2 , calling the previous template as a partial

{{#if nodes}}
<ul>
{{#each nodes}}
    <li>{{title}}
        {{> templates_linker_sub }}
    </li>
{{/each}}
</ul>
{{/if}}

output (success)

<ul>
    <li>node 1
        <ul>
            <li>node 1-1</li>
            <li>node 1-2</li>
        </ul>
    </li>
    <li>node 2</li>
</ul>

template with recursive partial
templates/linker/sub3 , calling itself as a partial

{{#if nodes}}
<ul>
{{#each nodes}}
    <li>{{title}}
        {{> templates_linker_sub3 }}
    </li>
{{/each}}
</ul>
{{/if}}

output (failure)

require.js times out, no output.

Am I wrong in assuming I can use recursive partials in this setup? Or did I miss something in writing my templates?

As a workaround, I defined a custom helper to apply a previously registered partial. The partial has already been compiled and is available through Handlebars.partials

define(['Handlebars', 'underscore'], function (Handlebars, _) {
    function partial(template, context, options) {
        var f = Handlebars.partials[template];
        if (!_.isFunction(f)) {
            return "";
        }

        return new Handlebars.SafeString(f(context));
    }
    Handlebars.registerHelper('recursivepartial', partial);
    return partial;
});

My modified template looks like

{{#if nodes}}
<ul>
{{#each nodes}}
    <li>{{title}}
        {{recursivepartial "templates_linker_sub" this}}
    </li>
{{/each}}
</ul>
{{/if}}

I know this is very old, but I just created a pull request to the require-handlebars-plugin repo that will fix the problem. At the moment, the plugin will parse the partial and add all referenced partials as a dependency (hence creating a circular reference.) See here: https://github.com/SlexAxton/require-handlebars-plugin/pull/229

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