Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables for a partial template

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?

like image 520
nkoren Avatar asked Aug 25 '13 09:08

nkoren


People also ask

What are template partials?

Template partials are small bits of reusable template or tag parts. You could create a Template partial for any number of purposes, anywhere that you need to reuse a small portion of a template, including partial or complete tags, other variables, etc.

What is variable template?

A variable template defines a family of variable (when declared at namespace scope) or a family of static data members (when defined at class scope).

What are partials used?

Partials are smaller, context-aware components in your list and page templates that can be used economically to keep your templating DRY.


1 Answers

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:

  1. The contents of Handlebars.partials can be strings or functions so you have to compile the partials on first use.
  2. Handlebars doesn't know if the partial will be text/plain or text/html so you'll need to call your helper in {{{...}}} or {{...}} as appropriate.
  3. This stuff isn't exactly documented (at least not anywhere that I can find) so you have to reverse engineer the Handlebars source and fumble about with console.log(arguments) to figure out how to use Handlebars.partials.
  4. You have to pass this by hand when you call the helper.

Fear not, it isn't really that complicated. Something simple like this:

Handlebars.registerHelper('partial', function(name, ctx, hash) {
    var ps = Handlebars.partials;
    if(typeof ps[name] !== 'function')
        ps[name] = Handlebars.compile(ps[name]);
    return ps[name](ctx, hash);
});

should do the trick. Then you can say:

{{{partial mode this}}}

and get on with more interesting things.

Demo: http://jsfiddle.net/ambiguous/YwNJ3/2/

like image 127
mu is too short Avatar answered Jan 01 '23 20:01

mu is too short