Hacker News new | ask | show | jobs
by ahoge 5029 days ago
>Thinking about this leaves me asking: why don't we just send the javascript template function to the client instead of doing all the template parsing/compiling on the client?

You can do this with Handlebars. I use a Grunt task to pre-compile all templates and then I just bundle them with the much smaller (it adds about 1kb or so) "vm" version of Handlebars.

Locally, I use the full version of Handlebars and regular non-compiled templates.

2 comments

Same here. I had some trouble with partials until I realized that you can just compile everything as a template and then do

    Handlebars.partials = Handlebars.templates
:)
I use:

    Handlebars.registerPartial("Foo", Handlebars.templates.Foo);
Your approach is kinda amazing. Makes me wonder why not all templates are automatically available as partial by default. Are there cases where you wouldn't want that?
I think the reason is Handlebars is supposed to look and act like Mustache and templates aren't named in Mustache, so they don't get named in "regular" Handlebars:

    var getHtml = Handlebars.compile("<div>yad yada...</div>");
And then following the rule of least surprise, if templates aren't partials during normal usage, then they shouldn't be with precompilation.

At least that's my guess. I didn't figure out my trick until digging through the source to figure out what was different. (Not much - just how/where they're stored & referenced.)

Ahm... yea, I forgot that I put them into `Handlebars.templates` myself if they aren't there yet (i.e. during development).
Perhaps I should have been a bit more specific. I don't really care so much about how you do it whether it's with jade or handlebars + grunt or whatnot (I happen to like jade). The main point is that pre-compiling and sending JS functions instead of strings is way faster and makes more sense.