Handlebars.render() ? #360

jbutz opened this Issue Nov 8, 2012 · 3 comments


None yet

4 participants

jbutz commented Nov 8, 2012

I'm currently looking at using handlebars as opposed to mustache since I would like to be able to have some logic in my templates.

With mustache.js where is the Mustache.render() function. It takes the template as the first argument and the second, optional, argument is the object to pass in with data.

I've created a function that approximates this in handlebars. Is there a function I am missing that does this, or some reason I shouldn't do this?

Here is a jsFiddle: http://jsfiddle.net/jasonbutz/6Vvb4/

Here is what I guess it would look like if added to Handlebars jbutz/handlebars.js@2fcb09e


There's nothing inherently wrong with having a convenience function that wraps Handlebars.compile(tpl)(data).

However, if you really care about performance then you should precompile your templates on the server and ship them to your frontend.

On the other hand, if precompiling your templates server-side isn't an option, then a convenience Handlebars.render() method is a good way to enforce your own template caching strategy to prevent unnecessary re-compilation. (Although Handlebars may already do this itself. @wycats is that true?)


Handlebars.render = Handlebars.render || function(tpl, data) {
    data = data || {};
    var compiled = Handlebars.render.cache[tpl];
    if (!compiled) {
        // Uncached template
        compiled = Handlebars.compile(tpl);
        Handlebars.render.cache[tpl] = compiled;
    return compiled(data);
Handlebars.render.cache = {};
  1. @mpetrovich That function is absolutely beautiful. I am not sure how cacheing templates never occurred to me, but good on you. I might borrow that function.

  2. @jbutz There's really no way to actually implement a Handlebars.render() function natively that would be any easier than a simple convenience function like @mpetrovich wrote above. You still have to pass the full template name and all the data, so you have to figure out what you want more: a) a convenience method that you write that you can make cooperate exactly the way you want it or b) a native Handlebars method that looks prettier but is not as maleable as a convenience method would be.

@kpdecker kpdecker was assigned Apr 7, 2013
kpdecker commented Nov 3, 2013

@mpetrovich handlebars does not cache templates. This can be a fairly expensive operation as you need to create a hash mapping the template source to the compiled output, both of which can end up being quite large.

Closing this request as users can implement their own version of render and I'd prefer that we prioritize things like the precompiler and named template access, vs. the more expensive content-based template access.

@kpdecker kpdecker closed this Nov 3, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment