Stilltorik
Stilltorik

Reputation: 1692

Handlebars helper: how do you run code after the template was rendered?

I am writing an application using handlebars, but no Meteor or Ember.

I am writing a helper which needs to run some code after the html was rendered, in order to attach onclicks to some dom elements. Is there a way to do that in the helper, without relying on an ugly setTimeout or something similar?

I found the solution for Meteor-based applications, but not when only handlebars is used.

Template:

{{#autocomplete config}}{{/autocomplete}}

Helper:

Handlebars.registerHelper('autocomplete', function(config) {
  return autocompleteTemplate();
});

Upvotes: 2

Views: 1574

Answers (1)

jball
jball

Reputation: 25014

I couldn't find anything built in that would do this, so I ended up wrapping the Handlebars.compile in a helper function that could do post-processing to rendered templates.

function compileWithExtras(template, options) {
    var template = Handlebars.compile(template, options);
    return function() {
        var rendered = template.apply(null, arguments);
        //do your post processing here
        return rendered;
    };
}

var exampleTemplate = compileWithExtras(document.getElementById("foo").innerHTML);
var postProcessedHtml = exampleTemplate(data);

If you're precompiling templates then you will need to target Handlebars.precompile which will be a little trickier, though a simple replace('return buffer;','return postProcess(buffer);') may be all that's needed, e.g.,

    function postProcess(buffer) {
    //do your post processing here
    return buffer;        
}   

function precompileWithExtras(template, options) {
    return Handlebars.precompile(template, options)
        .replace('return buffer;','return postProcess(buffer);');
}

Upvotes: 1

Related Questions