Everything

SlexAxton edited this page Sep 2, 2011 · 1 revision
Clone this wiki locally

Sproutcore Handlebars Templates!

Why?

During the development of your app, you can probably either just include your templates in your page, or pull them in asynchronously. In the final build of your app, both of these solutions are less than ideal from a performance perspective.

Enter, precompiled templates. Sure they end up being a touch bigger, but they can be easily rolled up into your build files, and included along with the app. If you use a dependency management tool along with sproutcore (since they're still working on their's), then the build tool could even be selective at which templates need to be compiled and included. You then save precious cpu cycles when your app loads, because you don't have to parse, and compile templates on the fly. It's not much, but it counts.

How

Sproutcore.Handlebars is really very similar to Handlebars standalone. They maintain a data buffer throughout all the templates in order to give you your live data performantly, and it also adds in a few little sproutcore calls sprinkled here and there. These are mostly obvious from the way they recreate the few objects that they do. (a SC.Handlebars = SC.create(Handlebars) shows that it's really just a small extension.) So most changes, and things will still be tracked in the Handlebars repo, etc. Check out the ./lib/main file to see exactly what gets overridden.

Integration

I have integrated this in with RequireJS using a require plugin to manage how the templates get included. It works well if you've bought into the require system. I've added it to the ./extras/ folder. You use it like you would the text! plugin, but it automatically registers your templates to SC.TEMPLATES and it automatically is handled in the build (assuming you have sc-handlebars installed). That means that while you are developing, you can edit the templates and their changes are reflected immediately, but when you run a build with r.js the plugin knows to precompile the templates and inject module versions into your code. Pretty nifty!

require( [ 'tmpl!templates/myTemplate.handlebars' ], function () {
  // in here SC.TEMPLATES.myTemplate now exists and is compiled for use.
  // feel free to use views that require the myTemplate template
});

Thanks

Thanks to Tom Dale, Yehuda Katz, @kpdecker, and Daniel Marcotte for the love and support of a thousand narwhals.