Express Handlebars 'partial' helper

2019-09-02 02:33发布

问题:

I want to implement something like this https://stackoverflow.com/a/18431716/1563880 with this lib

Here is my code:

var expressHandlebars  = require('express-handlebars');
var Handlebars = expressHandlebars.create({
    ....
    helpers: {
        partial: function(partialName, context, hash) {
            return Handlebars.getPartials()
                 .then(function(partials){
                     return partials[partialName](context, hash);
                 });
        }
    }
})

and use it in this way:

{{{partial partialName this}}} <!-- partialName is a variable -->

but result is [object Object] and this object is Promise instance.

How can I get template content?

回答1:

Final code should be like this:

var expressHandlebars  = require('express-handlebars');
var Handlebars = expressHandlebars.create({
    ....
    helpers: {
        partial: function(partialName, context, hash) {
            return Handlebars.partials[partialName](context, hash); //changes
        }
    },
    ....
});

Handlebars.getPartials()
    .then(function(partials){
        Handlebars.partials = partials;
    });

Please, correct me if I wrong