Glo
Glo

Reputation: 604

Append variable to partial name in handlebars (mustache)

I am using handlebars with grunt assemble, say I have a page that has a data field called 'page', can I pass that data field to the name of a partial (in another partial)?

Eg:

Upvotes: 4

Views: 1464

Answers (1)

raidendev
raidendev

Reputation: 2809

You can not pass variable as partial name usual way. There is two possible solutions:

1) If you know all possible names you can statically generate flat template and use it as you want.

Initial data:

{
    "names": [
        { "name": "dashboard-one" },
        { "name": "dashboard-two" }
    ]
}

Static template:

{{#each names}}
    \{{#if name.{{name}} }}
        \{{> sidebar-{{name}} }}
    \{{/if}}
{{/each}}

will produce:

{{#if dashboard-one }}
    {{> sidebar-dashboard-one }}
{{/if}}

{{#if dashboard-two }}
    {{> sidebar-dashboard-two }}
{{/if}}

Then you pass name 'dashboard-one' in template context:

{ "name": "dashboard-one" }

and get partial sidebar-dashboard-one executed.

2) Write custom helper. Handlebars internally use method Handlebars.VM.invokePartial to invoke partials. See, how it works.

Upvotes: 1

Related Questions