Using variables for a partial template

落花浮王杯 提交于 2019-12-03 01:45:50

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/

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.

{{> (whichPartial) }}

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 the lookup helper.

 {{> (lookup . 'myVariable') }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!