ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.32k stars 382 forks source link

Add ability to create template from string #205

Open pstuart opened 7 years ago

pstuart commented 7 years ago

Couldn't figure out a way to create a template from a string vs only reading from a directory. This would be very handy to have as the standalone version of handlebars has it.

shukriadams commented 6 years ago

I just posted another fix to a sort-of related issue, but you might be able to do this with a custom helper var Hbs = require('express-handlebars');

_helpers.partialFromString = function (markup, data, options) {

    var hbs = Hbs.create({});
    var template = hbs._compileTemplate (markup);

    // call inner nested helpers, this might not be necessary for you
    options.fn(options.data.exphbs);

    return template(data, options.data.exphbs, options);
};

and then call it with

{{#partialFromString "<div>{{text}}</div>" someModel}}{{/partialFromString}}

with your calling view having "someModel" in its data context.