Node.js server-side compile Hogan.js templates

If you are using Node.js with Hogan.js you want to compile your templates on the server.
With Node.js you can create a route which looks like this:

Include it like: <script src=’templates’ type=’text/javascript’></script>
Templates are in the T namespace and can be renderered like this:

3 comments to Node.js server-side compile Hogan.js templates

  • Luke Galea

    I adapted this for javascript rather than coffeescript. It’s up at https://github.com/lukegalea/express-hogan-precompile-boilerplate

  • Baz

    I adapted this into a grunt.js task. It’s a bit different as I wanted to use paths to template files with wildcards, and grunt has a few utils to help with this; also I found the default hogan exception needs augmented with the name of the template, since you can’t tell where it is in the loop. (it’d be nice to have line/col numbers too):

        grunt.registerMultiTask( 'hogan', 'Precompile with `hogan.js`', function() {
            var Hogan = require('hogan.js'),
            path = require('path'),
            data = this.data,
            result ="";
     
            var templates = grunt.file.expand(data.templates);
            templates.forEach(function(template) {
                var name = path.basename(template, path.extname(template));
                try {
                    result += "\nT['" + name +"']=" + 
                        Hogan.compile(grunt.file.read(template).toString(), {asString:true});                
                } catch (error) {
                    grunt.log.writeln("Error compiling template " + name + " in " + template);
                    throw error;
                }
            });
            grunt.file.write(data.output, result);
        });

    To use, you’d define a task something like this:

            hogan: {
                site: {
                    templates: ["templates/*.hogan"],
                    output: "target/templates.js"
                }
            }
  • Great, thanks for sharing!