requirejshandlebars.jsclient-side-templating

How to use precompiled templates in Handlebars with RequireJS?


I'd like to precompile my Handlebars templates, but I'm not sure how this works in development mode.

Is it common practice have some background process like Guard running to constantly monitor changes to Handlebars template files?

I'm using RequireJS to pull in templates; e.g.:

define(['jquery', 'handlebars', 'text!templates/my_template'], function($, Handlebars, myTemplate) {

  // ...

  var data = {"some": "data", "some_more": "data"};
  var templateFn = Handlebars.compile(myTemplate);
  $('#target').append(templateFn(data));

  // ...

});

So I understand once templates are precompiled, one would do this:

define(['jquery', 'handlebars'], function($, Handlebars) {

  // ...

  var data = {"some": "data", "some_more": "data"};
  var template = Handlebars.templates['my_template'];
  $('#target').append(template(data));

  // ...

});

Note the following about the in the second code snippet:

  1. The RequireJS module no longer pulls in the template.
  2. Handlebars.compile() is no longer used.

So typically would I have Guard running to keep my templates compiled whenever file system-level modifications happen to template files?

Basically my question is, is the intention for developers to do this?

if (development) {
  compile templates
}
else {
  use precompiled templates
}

I'm also using Rails, so maybe there is some black magic like sass-rails.


Solution

  • Have you take a look at Require.js Handlebars Plugin (https://github.com/SlexAxton/require-handlebars-plugin) or epeli's requirejs-hbs (https://github.com/epeli/requirejs-hbs) ?