I'm definitely missing something about the way Handlebars works. I need to call different partials depending on the value of a variable. Currently the only way I've found to do it is this:
<template name="base">
{{#if a}}{{> a}}{{/if}}
{{#if b}}{{> b}}{{/if}}
{{#if c}}{{> c}}{{/if}}
</template>
And in the corresponding JS:
Template.base.a = function () {
return (mode === "a");
}
Template.base.b = function () {
return (mode === "b");
}
Template.base.c = function () {
return (mode === "c");
}
...which strikes me as extremely verbose. What I'd really like to do is something like:
<template name="base">
{{> {{mode}} }}
</template>
In other words, the value of mode
would be the name of the partial that is called.
This seems like it must be a very common use-case, but I can't find any examples of this online. Where have I gone wrong?
The partials are stored in
Handlebars.partials
so you can access them by hand in your own helper. There are a few tricky bits here though:Handlebars.partials
can be strings or functions so you have to compile the partials on first use.text/plain
ortext/html
so you'll need to call your helper in{{{...}}}
or{{...}}
as appropriate.console.log(arguments)
to figure out how to useHandlebars.partials
.this
by hand when you call the helper.Fear not, it isn't really that complicated. Something simple like this:
should do the trick. Then you can say:
and get on with more interesting things.
Demo: http://jsfiddle.net/ambiguous/YwNJ3/2/
Update for 2016: Version 3 of handlebars added Dynamic Partials. From the docs:
It's possible to dynamically select the partial to be executed by using sub expression syntax.
Will evaluate
whichPartial
and then render the partial whose name is returned by this function.Subexpressions do not resolve variables, so
whichPartial
must be a function. If a simple variable has the partial name, it's possible to resolve it via thelookup
helper.