Rendering templates within helpers in handlebars

Viewed 15612

Because there seem to be no answer on this: Passing variables through handlebars partial yet, I'm currently working on a little workaround to get this work. So, the idea is to register a helper function which renders a specific template with possible values. A bit code makes it better to understand.

This is how a I'd invoke my helper:

<div>
    {{myHelper}}
</div>

This helper is registered with this little code:

hbs.registerHelper(name, function (args) {
    args = args || {};
    var template = hbs.compile(fs.readFileSync(__dirname + '/' + file, 'utf8'));
    return template(args);
});

I put this snippiet into a loop to register different helpers at once. This means 'name' and 'file' is given.

Okay now I'm able to do something like this:

// 'values' could be something like this:

var values = { headline: 'HEADLINE' }

<div>
    {{myHelper values}}
</div>

Within a helper I can now test if a certain values is given:

// myHelper template

<div>
    {{#if headline}}
    <h1>{{headline}}</h1>
    {{/if}}
    <p>Lorem ipsum</p>
</div>

This little workaround works for me, but there is one problem. Registering a helper as explained above, returns a plain HTML escaped string. So, invocing a helper doesn't output a rendered HTML snippet. It outputs the HTML as an escaped string.

Does anybody of you have an idea how I can make my code snippet return the HTML as HTML?

/Pascal

2 Answers
Related