4

I think this question will give mine a little more context:

Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)

Basically I'm trying to learn the precompiling stuff, so I can save load time and keep my html documents neat. I haven't started it yet, but based on the above link, every template needs to have it's own file. Isn't that going to be a lot of links to load? I don't want to be making multiple HTTP requests if I don't have to.

So if someone could shed some light, perhaps offer an alternative where I can get the templates out of my html, but not have to load up 100 different template files.

Community
  • 1
  • 1
Rey
  • 3,217
  • 5
  • 29
  • 39

1 Answers1

6

Tools like Grunt.js allow you to have your templates and consume them too. For example, this file compiles the templates and then concatenates them into a single file:

module.exports = function(grunt) {
  grunt.loadNpmTasks("grunt-contrib-handlebars");

  // Project configuration.
  grunt.initConfig({
    // Project metadata, used by the <banner> directive.
    meta: {},

    handlebars: {
      dist: {
        options: {
          namespace: "JST",
          wrapped: "true"
        },
        files: {
          "templates.js": [
            "./fileA.tmpl",
            "./fileB.tmpl"
          ]
        }
      }
    }
  });

  // Default task.
  grunt.registerTask("default", "handlebars");
};

What I've yet to work out since I'm just getting started with pre-compiled templates is the workflow. I want to be able to have compiled templates when we're running a deployed version of the app but when doing development and debugging I'd much rather have my original individual files in uncompiled form so I can just edit them and reload the page.

Follow Up:

I wanted to come back to this after having worked out some of how to both have my pre-compiled templates when available and use individual templates which can be edited on the fly when people are doing development and debugging work and would like to have quick edit-reload-test cycles without doing Grunt builds.

The answer I came up with was to check for the existence of the JST[] data structure and then further to test and see whether a particular pre-compiled template is present in that structure. If it is then nothing further need be done. If it's not there then the template is loaded (we use RequireJS to do that) and compiled and put into the same JST[] array under the same name it would have if pre-compiled templates had been loaded.

That way when it comes time to actually use the template, the code only looks for it in one place and it's always the same.

In the near future I think we'll likely have RequireJS plugins to perform the test and load/compile code while keeping it simple for developers.

John Munsch
  • 19,481
  • 8
  • 40
  • 72
  • +1 this works, grunt has many other cool features to offer too! Eg: JSHint, watch etc http://gruntjs.com/plugins – Kagawa Apr 18 '13 at 10:12