简体   繁体   中英

Express.js custom template engine (plate)

I am trying to get plate template engine to work with express.js. My initial attempt was this:

app.register('.html', {
    compile: function (str, options) {
        var template = new plate.Template(str);
        return function(locals) {
            return template.render(locals, function(err, data) {
                return data;
            });
        }
    }
});

I see that the problem is that template.render doesn't return anything (undefined) but passes the data to a callback. I'm not sure how to make it work in this case as Express expects the compile function to return a function that directly returns a rendered template when called.

I was thinking perhaps I can use promises to solve this issue but had no success there either since the express code doesn't expect a promise to be returned. Im not too up to speed on promises so I may just be doing it wrong:

app.register('.html', {
    compile: function (str, options) {
        var promise = new Promise();
        var template = new plate.Template(str);
        return function(locals) {
            template.render(locals, function(err, data) {
                promise.resolve(data);
            });
            return promise;
        }
    }
});

Here is an example of a custom implementation that does works. The difference is that underscore templates template() function directly returns the rendered string like so:

app.register('.html', {
    compile: function (str, options) {
        var template = _.template(str);
        return function (locals) {
            return template(locals);
        };
    }
});

I'd really like to use Plate templates since the {% block %} tag is so awesome. Any help is appreciated.

pertinent documentation:

plate's github docs

express.js app.register docs

The creator of plate promptly added a patch to the project to make it compatible with express after I asked this. plate@0.0.13+ has the change and you can see implementation details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM